Nuxt with laravel sanctum recieve "Unauthenticated" message

Viewed 2308

I'm trying to use Laravel sanctum with NuxtJS. The problem is I'm able to pass the get csrf and login but when i try to access the api/user, I get "Unauthorized" message. They say i should set SESSION_DRIVER to cookie but it's still the same. I'm using xampp so I'm running the laravel on localhost:8000 and nuxtjs on localhost:3000. Thanks in advance.

Unauthenticated

Laravel API

.env

SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost

config/cors

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

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,

api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
   return $request->user();
});

NUXT JS

nuxt.config.js

axios: {
     baseURL: "http://localhost:8000/",
     credentials: true
},
auth: {
   redirect: {
       login: '/login',
       logout: '/',
       callback: '/login',
       home: '/'
   },
   strategies: {
          local: {
             endpoints: {
                login: { url: '/login', method: 'post', propertyName: false },
                user: { url: '/api/user', method: 'get', propertyName: false }
             },
             tokenRequired: false,
             tokenType: false
          }
   },
   localStorage: false
},

Login.vue

export default {
data(){
    return{
        email:'',
        password:''
    }
},
components: {

},
methods:{
    login(){
        this.$axios.get('/sanctum/csrf-cookie', {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            withCredentials: true,
        })
        .then( function(){
            this.$auth.loginWith('local', {
                data: {
                    email: this.email,
                    password: this.password
                },
            });
        }.bind(this))
    }
},
mounted(){  
}
}
</script>
1 Answers

in nuxt.config.js, check local server port like this :

  auth: {
    strategies: {
      'laravelSanctum': {
       provider: 'laravel/sanctum',
       url: 'http://localhost:8000'
       },
    },
  },

  axios: {
    baseURL: 'http://localhost:8000',
    credentials: true
  },

if true:

in .env file check this :

SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:3000

then check your laravel kernel.php file and add this class if dosnt exist:

'api' => [
        EnsureFrontendRequestsAreStateful::class,
 ]
Related