qirolab / nuxt-sanctum-authentication

Nuxt 3 module for seamless Laravel Sanctum authentication with SSR support.
https://qirolab.github.io/nuxt-sanctum-authentication/
24 stars 1 forks source link

Got 401 when getting user after successful login #5

Closed khtodod closed 2 weeks ago

khtodod commented 2 weeks ago

Hi, I'm experiencing an issue where, after a successful login, the following request to retrieve the authenticated user returns a 401 Unauthenticated error. Below are my configurations for cors.php, .env, and nuxt.config.ts. I'd appreciate any guidance on resolving this.

// config/cors.php
<?php
declare(strict_types=1);
return [
    'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'register', 'logout'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => true,
];
# .env
SANCTUM_STATEFUL_DOMAINS=localhost:3000,localhost:8000
SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=localhost
// nuxt.config
export default defineNuxtConfig({
  laravelSanctum: {
    apiUrl: process.env.NUXT_PUBLIC_API_BASE || "http://localhost:8000"
  }
});

Issue Details

After successfully logging in, the following request to get the authenticated user's data results in a 401 response. The cookies are present in the request headers, and the CSRF token seems to be correctly set. Here are a few additional points:

Laravel App: Running on localhost:8000 Nuxt App: Running on localhost:3000 Sanctum Configuration: Using cookie-based authentication mode. I suspect this might be related to session cookies or CSRF configuration, but I've followed the documentation as closely as possible. Do you have any suggestions on what might be causing this 401 Unauthenticated error?

hkp22 commented 2 weeks ago

You may have forgotten to add the statefulApi middleware method in your application's bootstrap/app.php file. This can be critical for correctly handling stateful requests.

->withMiddleware(function (Middleware $middleware) {
    $middleware->statefulApi();
})

If you are still facing the issue, feel free to check out this detailed tutorial: Nuxt 3 + Laravel Sanctum Authentication Guide, where I have explained the process step-by-step.

Good luck! Let me know if you have any other questions!