Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting 401 unauthorized for Laravel sanctum

I am using Laravel Sanctum with Vuejs SPA. Both reside on same top level domain

Laravel backend : app.demo.localhost
Vue SPA : app-spa.demo.localhost

Login and logout (endpoints) are working correctly when called from VueJS SPA using axios and XSRF-TOKEN is succesfully set, but when I call other api end points it gives me 401 unauthorized.

In axios this is being set

axios.defaults.withCredentials = true;

I have the below configurations

In Laravel .env

SESSION_DRIVER=cookie
SESSION_DOMAIN=.demo.localhost
SANCTUM_STATEFUL_DOMAINS=app-spa.demo.localhost

In Routes/Api.php

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

In cors.php

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

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,

Could someone help me out please?

like image 880
MOHAMMED ABDUL HASEEB Avatar asked Apr 25 '20 05:04

MOHAMMED ABDUL HASEEB


People also ask

Is laravel sanctum secure?

Laravel Sanctum offers an immaculate, secure, blazingly fast, lightweight authentication system for single-page applications (SPA), mobile applications, and simple, token-based APIs. Sanctum is a profound package that allows every user to generate multiple API tokens for their account independently.

What is Sanctum authentication in laravel?

Introduction. Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account.

Is laravel sanctum oauth?

Laravel Sanctum does not support OAuth2; however, it provides a much simpler API authentication development experience.


1 Answers

If you are using php artisan serve add the port number to SANCTUM_STATEFUL_DOMAINS. So if your port number is 8000:

SESSION_DRIVER=cookie
SESSION_DOMAIN=.demo.localhost
SANCTUM_STATEFUL_DOMAINS=app-spa.demo.localhost:8000

Your SANCTUM_STATEFUL_DOMAINS must match the url in your browser. The port number should not be on the SESSION_DOMAIN.

like image 164
Scot Avatar answered Sep 19 '22 13:09

Scot