armingdev's avatar

Sanctum SPA Auth

Hello,

I have installed fresh copy of Laravel (without any fronted scaffolding or auth package) and installed Sanctum for SPA Auth. So Im using Laravel as API and separated RectJS app on frontend. I have setup Sanctum as documentation said, and have problems with accessing routes witch are protected with 'auth:sanctum' middleware.

As you can see on pictures:

  1. sending GET to set cookies - GET '/sanctum/csrf-cookie'

https://ibb.co/2qmLbgj

As you can se it set me two cookies.

  1. sending POST on my /api/login

https://ibb.co/HhzK3Fp

Login success ..

  1. sending GET to /api/users witch is protected by 'auth:sanctum middleware

https://ibb.co/F4TBXpg

As you can see It dosnt allow me to open it and redirecting me to the login route. In this case, error that said "Route [login] not defined." is not a problem since its just a pointing me to login route that I didn't write (since I'm using /api/route). Real problem is why it doesn't allow me to access route.

AutController login route:


    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if (Auth::attempt($credentials)) {
            // Authentication passed...
            return response()->json(['message' => 'Login successful'], 200);
        }
    }

api routes:


Route::post('login', 'AuthController@login');

Route::middleware(['auth:sanctum'])->group(function () {

    Route::resources([
        'users' => 'UsersController',
    ]);
});

Also I have : cors.php

'supports_credentials' => true,

.env

SANCTUM_STATEFUL_DOMAINS=localhost,127.0.0.1
SESSION_DOMAIN=localhost

Did I miss something? Or maybe I can't test this trough POSTMAN?

0 likes
6 replies
nikolayandreev's avatar

Hi there, can you try these few things:

You need to set this in .env SESSION_DRIVER=cookie

When logging in from your spa you need to make a request for the csrf-token first

// '/sanctum/csrf-cookie' is located in root, so you might need baseURL set to false
axios.get('/sanctum/csrf-cookie').then(response => { 
                        return axios.post('/authenticate', {
                                email: this.email,
                                password: this.password
                            })
                            .then(res => {
                                // Redirect or save localstorage object, your choice...
                            })
                    }).catch(e => {
                        Show errors.
                    });
sos99's avatar

it is simple :

auth for web = cookies

auth for api = token

keep your logic in 'web' if you need to authenticate your user from it.

if you make API without authenticating your users is a sign that you can leave it on your API logic

Please or to participate in this conversation.