15

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

miken32
  • 42,008
  • 16
  • 111
  • 154
user3326941
  • 331
  • 1
  • 4
  • 14

13 Answers13

19

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
Hadayat Niazi
  • 1,991
  • 3
  • 16
  • 28
  • I used custom domain name for calling the backend and frontend like (backend) `api.devtest.test` (frontend) `devtest.test` What should be written on `SESSION_DOMAIN` ? – Shulz Jul 21 '21 at 02:44
  • 1
    @Shulz `.devtest.test` (note `.` at the beginning) – see https://laravel.com/docs/10.x/sanctum#cors-and-cookies – Dan Apr 01 '23 at 18:35
18

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-CSRF-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

Stanley Aloh
  • 360
  • 4
  • 11
12

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,
],
jrran90
  • 668
  • 12
  • 18
  • 3
    You nailed it! What you are suggesting also is into the docs, check here https://laravel.com/docs/8.x/sanctum#sanctum-middleware – Fernando Torres Nov 01 '21 at 19:45
8

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

Dharman
  • 30,962
  • 25
  • 85
  • 135
Marco Cazzaro
  • 661
  • 8
  • 13
5

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

SANCTUM_STATEFUL_DOMAINS=localhost
Luis Montoya
  • 3,117
  • 1
  • 17
  • 26
5

For anyone using Laravel Homestead, use your actual domain.

SANCTUM_STATEFUL_DOMAINS=homestead.test
Daniel
  • 138
  • 1
  • 7
4

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.

gitmiro
  • 116
  • 4
2

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

Peter Fox
  • 1,809
  • 2
  • 20
  • 34
2

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.

1

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.

António Cabral
  • 69
  • 1
  • 12
0

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.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Robert Lane
  • 11
  • 1
  • 2
0

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.

rootShiv
  • 1,375
  • 2
  • 6
  • 21
0

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}]
Subrata Mondal
  • 822
  • 7
  • 17