4

I have installed:

  • laravel v 7.30.4
  • nuxtjs v 2.15.7

After i login in my laravel sanctum with nuxtjs auth module, when nuxt try to get user, laravel response 401 error(Unauthenticated message).

My network status: enter image description here

My cookies status: enter image description here

api.php:

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

nuxt.config.js :

   auth:{
    strategies: {
      'laravelSanctum': {
        provider: 'laravel/sanctum',
        url: 'http://localhost:8000',
        endpoints:{
          login:{
            url:'/login'
          },
          logout:{
            url:'/api/logout'
          },
        },
        user:{
          property:false
        }
      },
    },
    redirect:{
      login: '/auth/login',
      logout:'/',
      home:'/'
    },
    cookie: {
      options: {
        sameSite: 'lax'
      },
    },
  },

LoginController.php :

    public function login(Login $request)
    {
        $user=User::where('phone_number', $request->phone_number)->first();
        if (Hash::check($request->password, $user->password)){
            $request->session()->regenerate();
            return response()->json(null, 201);
        }
        return $this->setStatusCode(422)->respondWithError('password','invalid pasword');
    }

.env :

SESSION_DRIVER=file
SESSION_LIFETIME=120
SESSION_DOMAIN=localhost

SANCTUM_STATEFUL_DOMAINS=localhost:3000

I don't know where is problem that i get 401 error!

Omid Reza Heidari
  • 658
  • 12
  • 27

4 Answers4

3

I had the same issue, the solution was to add localhost:8000 (laravel domain) to SANCTUM_STATEFUL_DOMAINS

SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8000,localhost:3000
2

you need to return your api token after logging in. and send it in every request that you use middleware('auth:sanctum') in laravel route.

more info about issuing tokens in sanctum

getting user requires token and if not provided it with throw 401 error.

fevid
  • 723
  • 6
  • 18
1

on your .env you can add this SESSION_SECURE_COOKIE=false

Ala Tarighati
  • 3,507
  • 5
  • 17
  • 34
0

Have you added the EnsureFrontendRequestsAreStateful to the api middleware groups within your application's app/Http/Kernel.php file?

use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

protected $middlewareGroups = [
  ...
  'api' => [
      EnsureFrontendRequestsAreStateful::class, // Add & import this class
      'throttle:60,1',
      \Illuminate\Routing\Middleware\SubstituteBindings::class,
  ],
];

This is necessary if you are using sanctum with an SPA app. This has been documented as part of the Installation

Also take a look at this section to see if the issue you are having is related to CORS in Sanctum

Abishek
  • 11,191
  • 19
  • 72
  • 111