amstech
amstech

Reputation: 398

Laravel sanctum unauthenticated

I am using Laravel sanctum in my project with angular as frontend. Getting unauthenticated from the second api request. Please let me know where am I going wrong

Frontend-> 127.0.0.1:4200

Backend-> localhost:8888

.env config

SESSION_DOMAIN=localhost SANCTUM_STATEFUL_DOMAINS=127.0.0.1

Added middleware auth:sanctum to the routes group in api.php

Ref: https://prnt.sc/rm9ejy

Upvotes: 20

Views: 53031

Answers (17)

farid teymouri
farid teymouri

Reputation: 191

Make sure you have used 'web' middleware too !!

Like : 'middleware' => ['web','auth:sanctum']

Sanctum with web Middleware:

  • Laravel Sanctum is designed to handle both token-based authentication (e.g., API tokens) and session-based authentication (e.g., for web apps).
  • For session-based authentication to work with Sanctum, the web middleware must be included. This middleware enables session cookies to be used for authenticating users.

Upvotes: 0

Ahmad Ahmad
Ahmad Ahmad

Reputation: 79

I think comments covered a big portion of the possible reasons, so I'm gonna just give a little tip because I've struggled with this and the answer was just to make sure that you didn't forget to add api/ before the actual API route.

Upvotes: 1

mohammad pourmami
mohammad pourmami

Reputation: 59

This solution worked for me.

In the app/Http/Kernel.php file and $middlewareGroups, add \Illuminate\Session\Middleware\StartSession::class in the api section as well.

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        \Illuminate\Session\Middleware\StartSession::class, // <========
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

Upvotes: 0

Daniel_Ranjbar
Daniel_Ranjbar

Reputation: 120

In my case, I was sending auth bearer header token to my backend, in an incorrect way. i had a next-JS project. I retrieved the cookie this way: const ACCESS_TOKEN = req.cookies.get('ACCESS-TOKEN'). the problem was that this method would url-encode the value. so that 268|0oyabZ7cPIR8gWbp8a0dRfFHQO5Kl9ocLPhdz8Rdc9f52c31 would be converted to 268%7C0oyabZ7cPIR8gWbp8a0dRfFHQO5Kl9ocLPhdz8Rdc9f52c31 and that would render me unauthenticated. i used decodeURIComponent function on the value and my problem was gone.

Upvotes: 0

Stanley Aloh
Stanley Aloh

Reputation: 437

For anyone having an Unauthenticated error, please ensure you follow these steps.

  • Send a GET request to /sanctum/csrf-cookie
  • Send a post request to web route /login to get authenticated

After this step, you will be successfully authenticated by auth:sanctum middleware in the WEB route or any resource route that needs CRSF token present.

[Why did this work]
Sending a GET request(empty request) to /sanctum/csrf-cookie enables laravel to send the fresh set cookies command to your browser to set a fresh CRSF token which can be found in your cookies. Axios and most library send this fresh token as part of headers X-XSRF-TOKEN by default, for regular ajax request, please include them explicitly in your headers or in form _token, else your SPA will still hit the 419(token expired) error

Other things to be aware of:

  1. Ensure your SESSION_DOMAIN is set to localhost
  2. SANCTUM_STATEFUL_DOMAIN is set to your sub domain/SPA with the port e.g localhost:8000

For the original question please ensure you maintain same domain. I mean use localhost for both. And set SANCTUM_STATEFUL_DOMAIN = localhost:4200

Edited

Also set SESSION_DRIVER

Upvotes: 23

Subrata Mondal
Subrata Mondal

Reputation: 852

This worked for me. The solution is adding this to .htaccess of root folder (not only inside the public folder)

# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Upvotes: 1

Ant&#243;nio Cabral
Ant&#243;nio Cabral

Reputation: 169

In case you have problems when going into production and/or have more than one subdomains and also use https don't forget that the port is 443 instead of the usual 80.

E.g.:

SANCTUM_STATEFUL_DOMAINS=*.example.com:443
SESSION_DOMAIN=.example.com

Lost days trying to figure out why the laravel, the spa or the android app were taking turns to fail, but never working all at the same time, until found that solution.

Upvotes: 3

Carroll Bradford
Carroll Bradford

Reputation: 41

Late in the game but just to help those that keep looking for this solution, most of the answers here have some truth, just have to put them together to make it work:

  • ENV file: SESSION_DOMAIN=localhost (or whatever your domains is)
  • in config->sanctum.php->stateful (if not already there): Sanctum::currentApplicationUrlWithPort()
  • in app/Http/Kernel.php API add as very first (this is important) : \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
  • in app/http/kernel API remove if there: \Illuminate\Session\Middleware\StartSession::class,
  • add to your api routes middleware: auth:sanctum

Also worth checking the guard settings under config->sanctum.php

that should do.

Upvotes: 4

rootShiv
rootShiv

Reputation: 1427

check if you had changed your guard in past. goto config/auth.php check if your provider model is same as your user model (or the model you using) for authentication. in my case i was using different guard and provider.

Upvotes: 0

jrran90
jrran90

Reputation: 695

Have you checked your Kernel.php? app/Http/Kernel.php

Make sure you uncomment \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, coz by default it is being commented

'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

Upvotes: 13

Robert Lane
Robert Lane

Reputation: 21

I had the same solution as Marco, adding the rewrite rule to my htaccess in public fixed it.

RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

FYI I am hosting this on Auzre Web App Service (linux), if anyone else is doing that.

Upvotes: 0

Peter Fox
Peter Fox

Reputation: 1849

The sanctum stateful domains require the port number as well.

e.g. SANCTUM_STATEFUL_DOMAINS=127.0.0.1:4200

Although in your case your screenshot shows it should be SANCTUM_STATEFUL_DOMAINS=127.0.0.1:4201

Upvotes: 2

Hadayat Niazi
Hadayat Niazi

Reputation: 2480

Add your domains, for example my API is running on localhost:8000 my client is running on localhost:3000 so my env setting looks like below

SANCTUM_STATEFUL_DOMAINS=localhost:8000,localhost:3000

also, add your session domain

SESSION_DOMAIN=localhost

Upvotes: 20

Marco Cazzaro
Marco Cazzaro

Reputation: 701

Two days of pain and despair to arrive at this conclusion: the Bearer token was not attached to the request, and that was because of my .htaccess configuration.

If you, like me, are not able to authenticate via API token, try to add this line on your .htaccess file in the public directory in your Laravel project:

RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Right after RewriteEngine On directive.

CREDITS: Laravel not detecting auth token sent in the header and JWT package

Upvotes: 9

gitmiro
gitmiro

Reputation: 126

Which version are you running? Since V2.4.0 you need to specify the port:

SANCTUM_STATEFUL_DOMAINS=localhost:4200

See this issue for more info.

Upvotes: 5

Daniel
Daniel

Reputation: 138

For anyone using Laravel Homestead, use your actual domain.

SANCTUM_STATEFUL_DOMAINS=homestead.test

Upvotes: 5

Luis Montoya
Luis Montoya

Reputation: 3207

From the screenshot you shared I see your domain is localhost and not 127.0.01, just do:

SANCTUM_STATEFUL_DOMAINS=localhost

Upvotes: 5

Related Questions