Laravel API middleware - How to retrieve current user without requiring authentication - laravel

I have the following route in my routes/api.php
Route::get('/games/{game}', 'GamesController#show')->name('api.games.show');
On client side, I already included Authorization bearer token header in every AJAX request.
How can I retrieve the value of the user associated with the token throught $request->user() without having to require authentication (without having to use ->middleware('auth:api'))
Basically what I want is to have one route that serves for both authenticated (with token) and non authenticated (without token) requests.

Related

laravel passport optional authentication

I have been using Laravel passport to response Api data, I want to response favorite status by user of product if a user login (token paste in header to validate with passport authentication Middleware). Is there a solution to determine if a user login or not without using Middleware "api" in route Api or separate Api url based user login and non user-login?
I just found out that without middleware we can use Auth::guard('api') to validate the bearer token, so just add authorization header with bearer token and check user in controller using Auth::guard('api')

Does Passport utilize guards not to authenticate users but to validate access tokens on routes where these tokens are required?

I'm a little bit confused by the documentation. It's said:
Passport includes an authentication guard that will validate access
tokens on incoming requests. Once you have configured the api guard to
use the passport driver, you only need to specify the auth:api
middleware on any routes that require a valid access token.
So it means that Passport utilizes guards not to authenticate users but to validate access tokens on routes where these tokens are required. Did I get that right?
In this case, validating the access token is authenticating the user. To understand why this is the case, let's walk through a simplified authentication flow using JWTs (let's ignore oAuth2 for a bit).
The user is logging in on the website. This triggers a POST /login request, with the username and the password in the request body.
The backend validates the users credentials. If the credentials are valid, it will issue a JWT, which will act as an access token. The JWT payload will contain some data that allows the backend to identify a user, e. g. the user id. The JWT then is signed with a secret that only the backend knows.
The backend will return the access token to the client, who has to include the access token in any subsequent requests to the server. Usually, the client will provide the token in the Authorization header.
When handling the next request from the client, the backend will extract the access token from the Authorization header and check its signature. If the signature is valid, the backend can be sure that the token data has not been manipulated, e. g. by changing the user id on the access token. With a valid signature, the backend can extract the user id from the tokens payload and set the User model for that specific id as authenticated. With an invalid signature, the backend will probably return something like 401 Unauthorized.

How to use laravel sanctum without typical laravel /login

I have been created PWA with NuxtJS,
then I'm going to use sanctum package, but I don't want to request to the typical Laravel /login route, because I have a customized api /login route which authenticates users with OTP, not by password!
So I'm wonder how can I use sanctum in this situation??
You can use Sanctum's token based authentication to achieve this. All you have to do is add the HasApiTokens trait to your authenticable model and issue new tokens for it on a successful login. So you would have a route which will accept phone number or email and perform a login action. This would trigger the application to send OTP to the user. You have to store the OTP somewhere on the system. Then create another endpoint where user's can send back the OTP they received. This route will then check if the provided OTP matches the one on the system and issue a token to the user.
$token = $user->createToken(<provide-a-token-name>);
Make sure to send back the plaintext token to the user using the plainTextToken function on the token instance. User's will need to add this token to requests as a bearer token in the Authorization header.

Laravel Vue JS JWT Implementation

I am trying to understand how an auth in a spa context with a jwt token should be implemented based on a Register / Login / Logout process. I have been searching on the web and have implemented at laravel side tymon jwt but I am confused about next step regarding register form and login form.
Do I understand well that when my user register for the first time on my website, this is at this time that the JWT token should be generated and recorded in a cookie ? If yes, is it Vue or Laravel which should record the JWT token in a cookie ? I suppose Vue ?! If yes, in which manner?
Other question: what happen if the user clear the browser cache and eliminate the cookie containing the JWT form his computer ? Does he need to register again to get a a new token ?? I am totally confused about the process.
Getting a more detailed and step by step process would help.
Thanks
The rough sketch for a JWT authentication works like this:
Registration - (optional | If the user is not registered) User fills the registration form which is posted to the register route, User account is created and the api responds with 201 ( content created)
Login - User uses his credentials to login to the app. The credentials are verified and a JWT token is issued and sent back to the user.
Vue handles the JWT Token and stores the provided token into cookies ( you can use js-cookie to handle this, usually in Vuex state )
The token is used with every request sent forth to the server, server verifies the Token and then the request proceeds.
Logging out requests the server to invalidate the token and then removes the token from the cookies.
You can use laravel passport, Laravel Sanctum or tymon/Jwt for token management.

Magic Link login with Laravel Sanctum

For my project I have a set of users that should only be able to login by requesting a Magic Link. So they have an email address but no password. To avoid security issues, my goal was to get this working without having to save an authentication token in LocalStorage.
I've tried setting this up the following way with Laravel Sanctum:
When requested, I create a token for the user and email them the plaintext version.
The user would open the link containing the token in the querystring.
I would attach the (Bearer) token with the Authorization Header.
The next step (I assumed) would be to call a custom /api/login endpoint that uses the 'auth:sanctum' middleware. The Bearer token would authenticate the user and then I would manually login the user with Auth::login(). After this the active Session would be used to authenticate the user, thus avoiding having to save the token in localStorage.
But I can't call the Auth::login() method manually without getting an error (BadMethodCallException: Method Illuminate\Auth\RequestGuard::login does not exist.).
I can't figure out why this isn't working, or maybe I am going at this all wrong?
if you sending Sanctum token to user via email so in 1st request you will get token from url and you can use that token to login to application like this
use Laravel\Sanctum\PersonalAccessToken;
public function login(Request $request)
{
$personalAccessToken = PersonalAccessToken::findToken($request->token);
$user = $personalAccessToken->tokenable;
auth()->login($user);
return redirect('/');
}

Resources