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

401 Unauthorized #3

Closed
AdmiralXy opened this issue Jun 22, 2021 · 3 comments
Closed

401 Unauthorized #3

AdmiralXy opened this issue Jun 22, 2021 · 3 comments

Comments

@AdmiralXy
Copy link

After successful registration and login, every route with middleware auth:sanctum returns a status code: 401 Unauthorized, what could be the problem?

@AdmiralXy
Copy link
Author

Ah, alright, if I run site with the php artisan serve, then everything is ok, but with my Apache server and virtual domain there is a 401 error, how can I fix this?

@HijenHEK
Copy link
Owner

HijenHEK commented Jun 22, 2021

hello , thank you for opening this issue .

the problrem you are facing is a consequence of an unmatch in the url happening between the frontend and the backend allowed stateful domains , the vue js front end will post to yourdomain/api/login , yourdomain should be avaible in the stateful array located in the app/config/sanctum.php ( so your backend can accept the cookie sent by the front end including in the headers of each request ) .
by default laravel will inlude the APP_URL env var which holds your url so you need to specify your app url but ( and this is what i missed ) it wont include the port number ! because the config here uses parse_url that why it will accept the .test cause it has no port extension ( it will take it from the env var ) but it will not accept the localhost:8000 cause the parse_url will ignore the port number .

FIX : add the url manually to your config/sanctum.php with the port number

/*
    |--------------------------------------------------------------------------
    | 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',
        'localhost,localhost:3000,localhost:8000,127.0.0.1,127.0.0.1:8000,::1,'.parse_url(env('APP_URL'), PHP_URL_HOST)
    )),

@AdmiralXy
Copy link
Author

Thank you very much for the quick response and detailed explanation! After adding the URL to the sanctum settings, everything started working as expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants