4

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

Hadayat Niazi
  • 1,991
  • 3
  • 16
  • 28

1 Answers1

1

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
ken
  • 13,869
  • 6
  • 42
  • 36
  • I added this line globally in bootstrap.js window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; also added stateful domains, but it did not work – Hadayat Niazi Apr 12 '21 at 11:58
  • X-Requested-With is for CORS request checking, so you still need to set the X-XSRF-TOKEN, which will be sent on each request you made subsequently to fulfill the CSRF requirement by Laravel – ken Apr 13 '21 at 04:06
  • can you please explain a little bit more, how can I fix this issue. – Hadayat Niazi Apr 13 '21 at 18:12