Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Hadayat's avatar

Authenticating a SPA using Laravel but getting 401 unauthenticated user.

Laravel Sanctum is successfully installed and setup too.

Web.php

 Route::middleware('auth:sanctum')->post('/login', 'Teacher\RegisterController@login')->name('teacher.login');

Controller.php

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

        if(Auth::attempt($credentials)){
            return "Success";
        }else{
            return response()->json([
                "error"=>"User does't exists"
            ]);
        }
    }

Login.vue

login(){
            axios.get('/sanctum/csrf-cookie').then(response => {
                this.form.post('/login')
                .then( response => {
                    console.log(response);
                })
                .catch( error => {
                    console.log( error );
                })
            });
        }

console response

{data: "", status: 204, statusText: "No Content", headers: {…}, config: {…}, …}

I am following the official doc, so Implemented everything which is needed but it still says unauthenticated, console response determines that my cookie is set. What is an error, what's going wrong

0 likes
20 replies
Hadayat's avatar

When I am going to login with the correct credentials, in the network tab it says the unauthenticated request.

Hadayat's avatar

This is the response of the cookie.

Request URL: http://localhost:8000/sanctum/csrf-cookie
Request Method: GET
Status Code: 204 No Content
Remote Address: 127.0.0.1:8000
Referrer Policy: strict-origin-when-cross-origin
Cache-Control: no-cache, private
Connection: close
Date: Thu, 04 Feb 2021 14:36:09 GMT
Date: Thu, 04 Feb 2021 14:36:09 GMT
Host: localhost:8000
Set-Cookie: XSRF-TOKEN=eyJpdiI6IlZXTHdEWlN4bWp4QXJkK0d4dFJZdmc9PSIsInZhbHVlIjoiQlVVMHRBTEY3ZmxBdTZCOVpOUDQ3NVdoTG9DTURIWDN3QjEwSnRwUkMwbURqRWIrTXk0Q3JTSWQ4YXVKclFVS050ME1pOHFubVI0TG5UV0ZSVUNhSjFVZkx0OWp3SkhZWWJNTk1aNjUzNysyeXVMN0w4eVFRNXNhZEFWV3NVb2giLCJtYWMiOiJhZDAxMmIwZTc0NTI4YTNlNTQwYTZjNDY5ZjI5MTQzZThiN2JhM2NjNTU5NTA3OTI1MWVkOWZmMWUyZGEzMjgzIn0%3D; expires=Thu, 04-Feb-2021 16:36:09 GMT; Max-Age=7200; path=/; samesite=lax
Set-Cookie: laravel_session=eyJpdiI6Ik1Wc2I3WW9RT0tMeGRaWnBmNjhXb0E9PSIsInZhbHVlIjoiQjQ0bmk1bWdxTFczVlJnK1JUNlJVN2hDdWRyU3ZrR2VSL0N5UFVENDZpN3Vna09meTJ3UFNIR0VSKzlSTEZCakpaeFhiOEVFM1BjWkpVNnR2U1BlalBrZk9BTzk3WTZaSGxKbTRzYTY1K2FFdXVhWVk1VGNQYU0zRlc1cFYveWkiLCJtYWMiOiIyZjNlY2E5ODAwZWM4NDZjODA5MGQxZTc4ZjExY2Q5YTA1NDEzYjlhMjJlMTNjODQ2ZGVkOTBmYjU0OGI1YWEzIn0%3D; expires=Thu, 04-Feb-2021 16:36:09 GMT; Max-Age=7200; path=/; httponly; samesite=lax
X-Powered-By: PHP/7.4.8

But it still says unauthenticated.

khalilm's avatar

I dont think your login route should be under the sanctum middleware. At that point, you have only received your CSRF token, you are not authenticated. So you need to have your route in your web middleware or change your cors.php file

Hadayat's avatar

@khalilm I set my web path in cors.php, also tried with api.php(I put my routes inside the api.php) This is my core file path:

'paths' => ['api/*'],

Still the same issue.

khalilm's avatar

Your route can reside in the api file but it cannot be under the sanctum middleware.

Pull it out of there and put it under a generic middleware with throttle.This is what I have done. But first just pull it out and see if it works.

khalilm's avatar

Oh and also my cors.php looks like this:

'paths' => ['api/*', 'sanctum/csrf-cookie'],

Although you seem to be getting the cookie.

khalilm's avatar

I have two middleware groups in my api.php file. A generic middleware like this:

Route::middleware(['throttle:6,1'])->group(function () {

    //USER SIGN IN
    Route::post('/login', 'App\Http\Controllers\Unrestricted\AuthorizeController@authenticate');
    Route::post('/logout', 'App\Http\Controllers\Unrestricted\AuthorizeController@unauthenticate');

});

and the other middleware that holds my sanctum guarded routes

Route::middleware(['auth:sanctum'])->group(function () {
	...GUARDED ROUTES HERE...

});
Hadayat's avatar

Already did this step but not work

khalilm's avatar

You removed the login route from web.php too?

Hadayat's avatar

Yes I removed it from the web.php

khalilm's avatar

It is not clear from your post, does it even reach your auth request in your login function? Have you logged your request to ensure that the email and password are being sent?

khalilm's avatar

One last thing, did you set

axios.defaults.withCredentials = true

on your axios instance?

Hadayat's avatar

I already did this to true. Yes I checked it without middleware it successfully logged in but when I put the middleware inside the route it says unauthenticated. Can you please drop your email so I'll contact you by email?

khalilm's avatar

As I said before, the login should not go in the sanctum middleware. AFAIK, sanctum requires an authenticated user not just a user that has a valid CSRF token. This is why it works outside your sanctum middleware.

Beyond this I cannot help you further. Perhaps, look at this video for more explanation https://youtu.be/uPKd3q-iaVs

Hadayat's avatar

@luisaduana yes I solved by defining session domain and sanctum statefull domain.

session_domain=localhost
sanctum_statefull_domain=localhost:3000
jhob101's avatar

@hadayat thank you for this, it helped me resolve the same problem.

Slight correction to the code in .ENV:

SESSION_DOMAIN=127.0.0.1
SANCTUM_STATEFUL_DOMAINS=127.0.0.1:8000

Please or to participate in this conversation.