#How i could make persisting jtw auth with laravel?

103 messages · Page 1 of 1 (latest)

earnest pollen
#

Im using tymon jtw library and i want to have a "persisting" auth, everytime the user log in he dont need to log out until he want but i searched and its unsafe create jtw with no expiration time, then how i could do it?

#

im using cookies for save the jtw btw

abstract dune
#

Not at all answering your question, but I'm wondering why you're using JWTs over Laravels default session and auth handling?

earnest pollen
#

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);
        }
    }
abstract dune
raw sphinx
earnest pollen
#

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)

raw sphinx
#

What is your web frontend? SPA?

earnest pollen
#

Spa

#

React spa + laravel Only api

#

and i would like also make refresh tokens but laravel docs dont explain how to do it

raw sphinx
#

And you want web and mobile to be able to do full auth?

earnest pollen
#

Yes

#

Its my first time using laravel

#

actually only strugglin with login

raw sphinx
#

Sanctum token doesnt need refresh because you can revoke it from the server.

earnest pollen
#

But i still dont understand

#

token is taken by frontend and saved in a cookie or how

raw sphinx
#

You can use localstorage. Just be very careful there's no xss vulnerability

#

Don't use shady libraries or unsanitized user input

abstract dune
#

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

earnest pollen
#

Sorry i dont understand difference in jtw vs sanctum

earnest pollen
#

i see a post "dont save tokens on localstorage"

raw sphinx
#

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.

earnest pollen
#

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?

abstract dune
#

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.

earnest pollen
#

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

raw sphinx
#

You need to decide whether web is going to use cookies or both web and mobile will use tokens.

earnest pollen
#

do you recommend 2 diferent endpoints?

#

or just one?

raw sphinx
#

Is the web frontend on the same domain as Laravel backend

earnest pollen
#

no

#

or well

#

yes

#

Only in domain

#

https:mydomain

#

all larvel api stuff i have it on /api

raw sphinx
#

Are all users going to register, verify email, reset password through the web frontend

earnest pollen
#

but also will can do it on mobile

raw sphinx
#

So no?

earnest pollen
#

i guess

raw sphinx
#

Users can register through mobile too or no

earnest pollen
#

yes

raw sphinx
earnest pollen
#

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'));
raw sphinx
#

You need to issue a sanctum token

#

And maybe you skipped rate limiting.

#

That will allow brute force attacks

earnest pollen
#

i will add cloudflare for that

#

later i add it

raw sphinx
#

Ok issue a token and give user the plain text token

earnest pollen
#

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

raw sphinx
#

But mobile apps don't have cookies

earnest pollen
#

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

raw sphinx
#

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.

earnest pollen
#

store on localstorage?

raw sphinx
#

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

earnest pollen
#

Ohhhhh okay okay

#

Now for persistent my user will be logged all the time he wants until i log him out?

raw sphinx
#

You can set expiration or leave it infinite

earnest pollen
#

i would like it infinite until he log out

#

like most of the apps

#

but it is safe?

earnest pollen
#

but what you would recommend me

raw sphinx
#

For a dating app I think infinite is fine

#

It's not banking

earnest pollen
#

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

raw sphinx
#

$token->plainTextToken

#

You return that to the user

#

And don't return the $user

#

mobile has something like localstorage idk what it's called

earnest pollen
raw sphinx
#

Yea then store that token in localstorage

earnest pollen
#

then i can get the user with

$user = $token->tokenable;
raw sphinx
#

No you use auth:sanctum middleware then $request->user()

raw sphinx
#

Send the token as a request header.
Authorization: Bearer _____

#

Then auth:sanctum middleware will protect your routes.

earnest pollen
#

Ohhhh thank you alotttt bro