#How i could make persisting jtw auth with laravel?
103 messages · Page 1 of 1 (latest)
Not at all answering your question, but I'm wondering why you're using JWTs over Laravels default session and auth handling?
I want to make a mobile app too
Then i use jtw
i searched a tutorial and do something like this:
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (!$accessToken = auth('api')->attempt($credentials)) {
return response()->json(['message' => 'Invalid credentials'], 401);
}
$refreshPayload = JWTFactory::sub(auth()->id())->make([
'exp' => now()->addDays(7)->timestamp,
]);
$refreshToken = $this->jwt->encode($refreshPayload);
return response()->json(['success' => true])
->cookie('access_token', $accessToken, 60, '/', null, true, true, false, 'Strict')
->cookie('refresh_token', $refreshToken, 10080, '/', null, true, true, false, 'Strict');
}
public function logout()
{
return response()->json(['success' => true])
->cookie('access_token', '', -1)
->cookie('refresh_token', '', -1);
}
public function refresh(Request $request)
{
$refreshToken = $request->cookie('refresh_token');
if (!$refreshToken) {
return response()->json(['message' => 'No refresh token'], 401);
}
try {
$payload = $this->jwt->setToken($refreshToken)->getPayload();
$user = auth()->getProvider()->retrieveById($payload['sub']);
if (!$user) {
return response()->json(['message' => 'Invalid user'], 401);
}
$accessToken = auth('api')->login($user);
return response()->json(['refreshed' => true])
->cookie('access_token', $accessToken, 60, '/', null, true, true, false, 'Strict');
} catch (\Exception $e) {
return response()->json(['message' => 'Invalid refresh token'], 401);
}
}
I'd recommend to use Laravel documented solutions instead. Sanctum is intended for mobile auth, https://laravel.com/docs/12.x/sanctum#mobile-application-authentication
I implemented Laravel's full auth system with sanctum tokens. You can copy https://github.com/BoilingSoup/sneeze
Got you brother
Hey
@abstract dune
I still on trouble
How i can make a single endpoint for web and mobile?
Also i want it to be secure
But i still have this problems how, actually im using laravel sanctum but the way of saving tokens is pretty hard
(for me)
What is your web frontend? SPA?
Spa
React spa + laravel Only api
and i would like also make refresh tokens but laravel docs dont explain how to do it
And you want web and mobile to be able to do full auth?
Sanctum token doesnt need refresh because you can revoke it from the server.
But i still dont understand
token is taken by frontend and saved in a cookie or how
You can use localstorage. Just be very careful there's no xss vulnerability
Don't use shady libraries or unsanitized user input
If you have access to cookies (i.e. a web browser), you don't need to deal with tokens at all. Laravel automatically uses cookies in that case
Sorry i dont understand difference in jtw vs sanctum
but isnt better cookies?
i see a post "dont save tokens on localstorage"
Not really. That is to protect tokens from XSS, but if you are already compromised with XSS you are screwed and the token isn't very useful to the attacker.
The attacker can just make requests on behalf of the user at that point.
Ok now let me understand
I Create a api endpoint /login
If all is success i return to the user a cookie with the laravel token and thats all?
That's what Laravel does, you don't need to do that.
But that assumes a web browser. If you're building a native mobile app, you don't have a web browser.
Im reading documentation but i dont get how to do a manual /login
Because in my app i verify also if the user is verified and and exist and that
You need to decide whether web is going to use cookies or both web and mobile will use tokens.
Is the web frontend on the same domain as Laravel backend
no
or well
yes
Only in domain
https:mydomain
all larvel api stuff i have it on /api
https://mydomain/api/ < laravel stuf
https://mydomain/view < react stuff
Are all users going to register, verify email, reset password through the web frontend
yes
but also will can do it on mobile
So no?
i guess
Users can register through mobile too or no
yes
Then I recommend you look through this code. That's what I implemented a few days ago.
https://github.com/BoilingSoup/sneeze
If your mobile only needed to be able to login/logout I would've suggest Breeze. But since you want the full auth flow you need more.
actually my code look like this bro:
# ALL OTher verifications
if(!Auth::attempt($credentials)){
return response()->json(new Response("error","Unauthorized", ["password" => "Contrasena incorrecta"]), 401);
}
return response()->json(new Response(
'success'
, 'Login success'));
You need to issue a sanctum token
And maybe you skipped rate limiting.
That will allow brute force attacks
Ok issue a token and give user the plain text token
like this?
$user = Auth::user();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json(new Response(
'success'
, 'Login success'));
i put in a cookie the access token
But mobile apps don't have cookies
oh then i make 2 different endpoints right?
$user = Auth::user();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json(new Response(
'success'
, 'Login success',
['token' => $token, 'user' => $user]
));
which option you recommend me
tbh is a dating app
You could but then you need to make 2 endpoints for all the auth endpoints. And the security benefit is not that great as I said earlier.
which one is the more factible option?
store on localstorage?
Yes just be careful with XSS
SPA will protect you from most XSS as long as you aren't using props like _dangerouslySetInnerHTML in react
Ohhhhh okay okay
Now for persistent my user will be logged all the time he wants until i log him out?
You can set expiration or leave it infinite
i would like it infinite until he log out
like most of the apps
but it is safe?
This is infinite
So it its all i need?
$user = Auth::user();
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json(new Response(
'success'
, 'Login success',
['token' => $token, 'user' => $user]
));
web -> localstorage
mobile -> idk place or memory
$token->plainTextToken
You return that to the user
And don't return the $user
mobile has something like localstorage idk what it's called
Yea then store that token in localstorage
then i can get the user with
$user = $token->tokenable;
No you use auth:sanctum middleware then $request->user()
Well I guess you could do that but Laravel has a cleaner way.
Send the token as a request header.
Authorization: Bearer _____
Then auth:sanctum middleware will protect your routes.
Ohhhh thank you alotttt bro