Laravel sanctum unauthenticated

試著忘記壹切 提交于 2021-02-04 18:28:09

问题


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


回答1:


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

SANCTUM_STATEFUL_DOMAINS=localhost



回答2:


For anyone using Laravel Homestead, use your actual domain.

SANCTUM_STATEFUL_DOMAINS=homestead.test



回答3:


For anyone having the Unauthentication error, please ensure you follow this 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 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:


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.




回答5:


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



来源:https://stackoverflow.com/questions/60843137/laravel-sanctum-unauthenticated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!