SPA authentication using sanctum failed with this error message: "Unauthenticated."

Viewed 1954

I am building SPA with Vuejs and Laravel, I installed the laravel sanctum to authenticate the user by its token.

Api.php

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

Login.Vue

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

Custom Controller

public function login(Request $request){

$credentials = $request->only('email', 'password');

        if(Auth::attempt($credentials)){
            return response()->json(Auth::user(), 200);
        }
}

I checked this without sanctum middleware it successfully logging the user, but I add the middleware inside the route it says your request is Unauthenticated. I implemented everything by following the official Laravel-7 doc, I don't why it says Unauthenticated, attaching the IMG for more detail.

enter image description here enter image description here

enter image description here

1 Answers

Make sure the X-CSRF-TOKEN or X-XSRF-TOKEN you gotten from csrf-cookie is appended to the HTTP request header to api/teacher/login. For Axios, you can set it with

axios.defaults.headers.common['X-XSRF-TOKEN'] = <the x-xsrf-token from csrf-cookie request>

Make sure to declare SANCTUM_STATEFUL_DOMAINS in .env with the port number. You can include multiple domain with it as well. SANCTUM_STATEFUL_DOMAINS='your-domain.test:8080,localhost:8000'

Without this you will encounter Session store not set issue due to middleware EnsureFrontendRequestsAreStateful is checking whether the request is from frontend or not. If it is from fronetned, then it will attach following middlewares to it

  • EncryptCookies
  • StartSession
  • VerifyCsrfToken
Related