8
votes

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

7

7 Answers

7
votes

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

  • Send a post 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 API route.

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

4
votes

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

SANCTUM_STATEFUL_DOMAINS=localhost
4
votes

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
3
votes

For anyone using Laravel Homestead, use your actual domain.

SANCTUM_STATEFUL_DOMAINS=homestead.test
3
votes

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.

0
votes

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

0
votes

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