I have a session login system for a few guards. I'm using Vue a lot and I came to the point where I need authentication in Vue in order to fetch and post data properly. The question is how could I get the authenticated session user to work with API. So in api.php I want to use a controller whose Middleware the authenticated user. I don't want to use Passport because I only have logins over the webpage and not API.
vue supports component also there is something called props which they are data that you can pass to your vue component what I would usually do is pass the authenticated user id to my vue component and then when I ever fire a request from vue component I will pass the current authenticated user to the backend and there I check if the id received with request is the same as the current authenticated user.
check the example below I will use the regular guard
loading vue component from blade
//loading vue test-component and pass the authenticated user
<test-component :authuser="{{Auth::(user)->id}}"></test-component>
vue component
<script>
export default {
props : ['authuser'], //should be the same name as you passed it
data(){
return {
}
},
created(){
axios.post('/api/test' , {
'authuser' : this.authuser
})
.then(res => {
console.log(res);
})
.catch(err => {
});
}
}
Api route
use Auth;
Route::post('api/test' , function($request){
if(Auth::user()->id == $request->authuser)
return 'you are authenticated';
else
return 'you are not authenticated';
});
Hope you find this helpful , Good luck.
Related
I want to get the currently logged in user whenever my React SPA starts, so I can show the user's information, but every time I try to get it from my Laravel back-end I get a 401.
I am using Laravel + Sanctum for my API, and using React in a different project for the front-end.
BACK-END:
I have the following in my AuthController controller:
public function user()
{
return auth()->user();
}
Inside my routes api.php I have the following route:
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::get('/user', [AuthController::class, 'user']);
Route::post('/logout', [AuthController::class, 'logout']);
});
My .env file contains the following:
SANCTUM_STATEFUL_DOMAINS=localhost:3000
SESSION_DOMAIN=localhost
FRONT-END:
I have a context that has the following:
useEffect(() => {
apiClient()
.get("/api/user")
.then((res) => {
setUser(res.data.user);
});
}, []);
and if you are wondering, my apiClient() comes from here:
import axios from "axios";
const apiClient = () => {
const api = axios.create({
baseURL: "http://localhost:8000",
withCredentials: true,
headers: {
Accept: "application/json",
},
});
return api;
};
export default apiClient;
This context is at the top level of the application.
I am not sure what's going on, my route /login is working as expected, I send the request and receive the user information as response which I set to a React state. On page refresh this state is removed because that's how Javascript works. I want to set it again using the useEffect mentioned above, so when the user loads the web app after closing the browser they can still see their information.
Thanks in advance!
To authenticate your SPA, your SPA's "login" page should first make a request to the /sanctum/csrf-cookie endpoint to initialize CSRF protection for the application:
axios.get('/sanctum/csrf-cookie').then(response => {
//Login...
});
For more information check https://laravel.com/docs/8.x/sanctum#spa-authentication
I'm building a SPA with Laravel in backend and VueJS2 as frontend provider.
The application will handle users with 3 kind of roles: UserRole1, UserRole2 and Admin.
When a user signup to the application, he select if he wants to be a user with Role1 or a user with Role2 (admin-user is set by me directly in the mysql database).
So in the database there is a table "users" with a field called "role":
UserRole1 => "role"=1;
UserRole2 => "role"=2;
Admin => "role"=7.
When an user login, I want to redirect him to his role-based dashboard, so I have 3 different Vue components and 3 routes, and I want to prevent an user with Role1 (or Role2) from access to Role2 or Admin dashboard. Obviously, if a guest try to access to the dashboard, it will be redirected to the login page, and if an authenticated user try to access guest pages (like the Register page), it will be redirected to the dashboard page.
I would like to set a "userRole" parameter for each route, as below:
{
path: '/app/userRole1/Dashboard',
component: DashboardUserRole1,
name: 'dashboardRole1',
meta: {
title: 'Dashboard Role1',
userRole: 1
},
},
{
path: '/app/userRole2/Dashboard',
component: DashboardUserRole2,
name: 'dashboardRole2',
meta: {
title: 'Dashboard Role2',
userRole: 2
},
},
{
path: '/app/Admin/Dashboard',
component: DashboardAdmin,
name: 'dashboardAdmin',
meta: {
title: 'Dashboard Admin',
userRole: 7
},
},
I've tried with Laravel Passport API and now I'm trying with JWT and websanova/vue-auth, so in the "Login" component there is a post request to the "api/auth/loign" route, that pass the data to the AuthController#authenticate method, that return a json response. But the vue-auth package is not so suitable for my needs, so I think that there could be a more efficient solution but actually I can't figure out how to write an appropriate code. I would like to know if you have some ideas.
A simple solution is to define an api route for retrieving information about the authenticated user. Laravel's default api.php routes file contains this route:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
You could modify it to include whatever information that your application needs to know about a user in order to handle routing logic:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user()->load('roles');
});
Then your flow looks like this:
Log in normally.
Immediately call /api/user, and store the response.
Use the stored roles to route to the correct view in your SPA.
If the confusion is around Step 3, then this stackoverflow question might help.
I'm currently building a laravel 5.4 powered page to manage users. I've done all basic pages such as home, login, register, dashboard using blade templating engine. Now I'm building the User Management page. I've successfully implemented VueJS for this particular page. All components are working perfectly.
Now the problem I'm facing now is using Axios to get logged in user data from API route. At first I'm using usual api route to get auth()->user() data but it doesn't work.
I've learned that I must use Laravel Passport to do this API operation.
These are the steps I made after that:
composer require laravel/passport
php artisan migrate
php artisan passport:install
Added the Laravel\Passport\HasApiTokens trait to your App\User model
Called the Passport::routes method within the boot method of your AuthServiceProvider
Set the driver option of the api authentication guard to passport
Added the CreateFreshApiToken middleware to your web middleware group
Edited bootstrap.js file like the following :
window.axios.defaults.headers.common = {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'X-Requested-With': 'XMLHttpRequest'
};
Axios Code :
axios.post('/api/getmydata', {
params: {
type: 'raw'
}
})
.then((response) => {
console.log(response);
}).catch((error) => {
console.log(error);
});
Changed route (api.php) :
Route::group(['middleware' => 'api'], function(){
Route::post('getmydata', 'ApiController#test');
});
Added function inside ApiController :
public function test() {
$user = Auth::user();
return $user;
}
The problem here is axios somehow return error: Unauthenticated
Is there anything wrong with my code?
Or is there any other way of achieving this? Thank you
Send the access token in the header of your API request:
Application Type :application/json
Authentication : Bearer [Access-Token]
I'm trying to implement private channel authorization with Pusher and Laravel.
The forms require a CSRF input field (randomized input name and value). Normally I use twig to insert them into the forms I put on the page.
How can I insert the csrf fields into the form data that Pusher sends when it tries to connect to the auth endpoint? It isn't present in the form data (but is present in the request header), so it's getting rejected by the laravel CSRF middleware.
If you're using Laravel, this isn't necessary, you shouldn't implement your auth endpoint like this. Your auth endpoint should be defined inside channels.php in the routes folder. For example
// routes/channels.php
Broadcast::channel('chat', function ($user) {
return Auth::check();
});
CSRF not necessary.
I'm making an app with Live Chat in Laravel 5 and I'm following this tutorial, https://github.com/dazzz1er/confer/tree/master I already followed all of them but I'm having an error in my web console:
Seems like it's making an ajax call on my url http://localhost/joene_/public/index.php/auth and since I don't have a route to handle that request, it says 404. I don't know if should make a route for it but what will I code on there? I have no idea. The tutorial doesn't even mention it.
Thanks
Whenever, you call Auth::check(), Laravel will verify if the user is authenticated by checking its session information.
What about Pusher? How will they know, which users are currently logged in on your laravel application?
The answer lies in the ajax call http://localhost/joene_/public/index.php/auth.
By calling the above URL, your laravel installation will let your Pusher application link with your users' laravel session.
Let's dive into some code:
1) Pusher Auth Controller
class PusherController extends Controller {
//accessed through '/pusher/'
//setup your routes.php accordingly
public function __construct() {
parent::__construct();
//Let's register our pusher application with the server.
//I have used my own config files. The config keys are self-explanatory.
//You have received these config values from pusher itself, when you signed up for their service.
$this->pusher = new Pusher(\Config::get('pusher.app_key'), \Config::get('pusher.app_secret'), \Config::get('pusher.app_id'));
}
/**
* Authenticates logged-in user in the Pusher JS app
* For presence channels
*/
public function postAuth()
{
//We see if the user is logged in our laravel application.
if(\Auth::check())
{
//Fetch User Object
$user = \Auth::user();
//Presence Channel information. Usually contains personal user information.
//See: https://pusher.com/docs/client_api_guide/client_presence_channels
$presence_data = array('name' => $user->first_name." ".$user->last_name);
//Registers users' presence channel.
echo $this->pusher->presence_auth(Input::get('channel_name'), Input::get('socket_id'), $user->id, $presence_data);
}
else
{
return Response::make('Forbidden',403);
}
}
}
2) JS used with Pusher
//replace 'xxx' below with your app key
var pusher = new Pusher('xxx',{authEndpoint : '/pusher/auth'});
var presenceChannelCurrent = pusher.subscribe('presence-myapp');
presenceChannelCurrent.bind('pusher:subscription_succeeded', function() {
alert(presenceChannelCurrent.members.me.info.name+' has successfully subscribed to the Pusher Presence Channel - My App');
});
Hope it helps you.