armingdev
1 week ago
295
2
Laravel

Sanctum SPA Auth

Posted 1 week ago by armingdev

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', '[email protected]');

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?

Please sign in or create an account to participate in this conversation.