Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Question] 401 error get user #191

Closed
mohamad4j opened this issue Oct 2, 2024 · 10 comments
Closed

[Question] 401 error get user #191

mohamad4j opened this issue Oct 2, 2024 · 10 comments
Assignees
Labels
bug Something isn't working

Comments

@mohamad4j
Copy link

mohamad4j commented Oct 2, 2024

Describe the bug

I can login successfully but it cannot get user. always I get 401. I think the token isn't set in header and I don't know why?
I checked all config for both laravel and nuxt

// REPLACE WITH YOUR FILE CONTENT!
export default defineNuxtConfig({
  compatibilityDate: '2024-04-03',
  devtools: { enabled: true },
  ssr: false,
  modules: ['nuxt-auth-sanctum'],
  sanctum: {
    baseUrl: 'http://localhost:8000/api', // Laravel API
    origin: 'http://localhost:8000', // Laravel API
    mode: "token",
    redirectIfAuthenticated: false,
    redirectIfUnauthenticated: false,
    endpoints: {
      csrf:"http://localhost:8000/sanctum/csrf-cookie",
      login: '/auth/login',
      user: '/auth/user',
      logout: "/auth/logout",
    },
    redirect: {
      onLogin: false,
      onAuthOnly: "/login",
      keepRequestedRoute: true,
    },
  },
})
});

Laravel sanctum config:

<?php

use Laravel\Sanctum\Sanctum;

return [

    /*
    |--------------------------------------------------------------------------
    | Stateful Domains
    |--------------------------------------------------------------------------
    |
    | Requests from the following domains / hosts will receive stateful API
    | authentication cookies. Typically, these should include your local
    | and production domains which access your API via a frontend SPA.
    |
    */

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s',
        'localhost,127.0.0.1,127.0.0.1:8000,::1',
        Sanctum::currentApplicationUrlWithPort()
    ))),

    /*
    |--------------------------------------------------------------------------
    | Sanctum Guards
    |--------------------------------------------------------------------------
    |
    | This array contains the authentication guards that will be checked when
    | Sanctum is trying to authenticate a request. If none of these guards
    | are able to authenticate the request, Sanctum will use the bearer
    | token that's present on an incoming request for authentication.
    |
    */

    'guard' => ['web'],

    /*
    |--------------------------------------------------------------------------
    | Expiration Minutes
    |--------------------------------------------------------------------------
    |
    | This value controls the number of minutes until an issued token will be
    | considered expired. This will override any values set in the token's
    | "expires_at" attribute, but first-party sessions are not affected.
    |
    */

    'expiration' => null,

    /*
    |--------------------------------------------------------------------------
    | Token Prefix
    |--------------------------------------------------------------------------
    |
    | Sanctum can prefix new tokens in order to take advantage of numerous
    | security scanning initiatives maintained by open source platforms
    | that notify developers if they commit tokens into repositories.
    |
    | See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
    |
    */

    'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),

    /*
    |--------------------------------------------------------------------------
    | Sanctum Middleware
    |--------------------------------------------------------------------------
    |
    | When authenticating your first-party SPA with Sanctum you may need to
    | customize some of the middleware Sanctum uses while processing the
    | request. You may change the middleware listed below as required.
    |
    */

    'middleware' => [
        'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
        'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,
        'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
    ],


];

corse.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */
    'Accept' => "application/json",

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

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];

Screenshot 2024-10-02 at 10 17 30 AM
Screenshot 2024-10-02 at 10 17 40 AM

@mohamad4j mohamad4j added the bug Something isn't working label Oct 2, 2024
@manchenkoff
Copy link
Owner

manchenkoff commented Oct 2, 2024

Hey @mohamad4j to properly use token mode, you should fix your nuxt.config.ts

export default defineNuxtConfig({
  compatibilityDate: '2024-04-03',
  devtools: { enabled: true },
  ssr: false,
  modules: ['nuxt-auth-sanctum'],
  sanctum: {
    baseUrl: 'http://localhost:8000/api', // Laravel API
    mode: "token",
    redirectIfAuthenticated: false,
    redirectIfUnauthenticated: false,
    endpoints: {
      login: '/auth/login',
      user: '/auth/user',
      logout: "/auth/logout",
    },
    redirect: {
      onLogin: false,
      onAuthOnly: "/login",
      keepRequestedRoute: true,
    },
  },
})

and make sure that your Nuxt application URL is not included in the stateful domain list.

Please, also change sanctum.logLevel to 5 and send me the logger output from both CSR (browser console) and SSR (server console) modes.

@mohamad4j
Copy link
Author

Screenshot 2024-10-02 at 12 56 29 PM
Screenshot 2024-10-02 at 12 58 41 PM
Screenshot 2024-10-02 at 12 58 57 PM

@manchenkoff
Copy link
Owner

@mohamad4j I see, looks like you are using an old version, please upgrade to 0.4.17 and try again

@mohamad4j
Copy link
Author

Screenshot 2024-10-02 at 1 04 18 PM
I upgraded it but still doesn't work

@manchenkoff
Copy link
Owner

I upgraded it but still doesn't work

I meant to send the logs with a new version

@mohamad4j
Copy link
Author

mohamad4j commented Oct 2, 2024

Screenshot 2024-10-02 at 1 08 41 PM

Screenshot 2024-10-02 at 1 09 05 PM

Screenshot 2024-10-02 at 1 09 16 PM

@manchenkoff
Copy link
Owner

@mohamad4j
The potential reason for the issue should be fixed now in 0.4.18, please try upgrading and let me know if it helps

@mohamad4j
Copy link
Author

mohamad4j commented Oct 2, 2024

Yep. the problem solved. thanks a bunch! in cookie mode still hav
Screenshot 2024-10-02 at 4 01 57 PM
e problem. Should I change anything in configs?

@manchenkoff
Copy link
Owner

manchenkoff commented Oct 2, 2024

@mohamad4j yes, for cookie you should use different middleware on Laravel side (include domain into stateful list) and make minor changes in module config, check details here - https://manchenkoff.gitbook.io/nuxt-auth-sanctum/authentication/spa-cookie

@manchenkoff
Copy link
Owner

I'm closing this for now, feel free to create a new one if new issue appears.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants