@jamols09 if you’re using the default Laravel auth, the user will be available to you in the controller using Auth::user(), auth()->user(), or on the request, request()->user().
How to identify User via API
I am using VueJs + Laravel and I have already setup the authentication and then the user will be redirected after login. /user/profile
My question is that how do I know which user is currently accessing the page? Like.. if the user has already setup their information such as name, address, etc. I want those information to be displayed (if they have filled up) when user visits their profile page.
Do I send the authentication token in header? If so how do I handle it on my api controllers. Do I have to create a middleware so that I can process the token header then get the user information who is visiting a page?
FIrst of all, because you have your frontend and backend separate, to display any information (someone's profile in this case) you have to request it to the backend.
In vue you should call api/user/profile (or whatever your route looks like on Laravel) to get the user information. For that to work, the user should be authenticated.
On the Frontend
You are using passport, but I will also include Laravel Sanctum authentication for other's to find.
Laravel Sanctum (SPA)
If you are using Laravel Sanctum with SPA Authentication, that requires no additional input on vue as it uses the plain ol' sessions.
Laravel Sanctum (API)
If you are using Laravel Sanctum with API Authentication, you need to provide an Authorization header containing the token you got at login. Best practice is to store this token somewhere on the client's browser. Then, you simple include the followin header on any authenticated requests:
{
"headers": {
"Authorization": "Bearer [TOKEN-PROVIDED-BY-SANCTUM]"
}
}
Laravel Passport
Haven't used Passport as Sanctum is better suited for this, but as far as I know, on vue's side this works identically to Laravel Sanctum's API Authentication. You get a token, you store it somewhere, and then send it in the Authorization header. I strongly suggest you switch Passport to Sanctum if you can
On Laravel
On Laravel's side, you simple use the app normally. Remember to go to auth.php and change defaults.guard to api if using passport, or sanctum if using either of Sanctum's Authentication methods. This will tell laravel to "look for your user" using the passport/sanctum authentication method. Alternatively, if for some reason you need it set to web, which you probably dont, simply specify the guard any time you want to use Auth.
// Using helpers
auth()->guard('sanctum')->user()
// Using Auth Facade
Auth::guard('sanctum')->user()
Please or to participate in this conversation.