xuncanzhe
V2EX  ›  PHP

Laravel 登录状态跨域

By xuncanzhe at 2020 年 8 月 6 日 · 3450 次点击

前后端分离测试,本地 POST 后台登录正常,刷新浏览器后 Auth::check() 仍是未登录状态。请问想要登录状态也能保存需要怎么设置?

跨域已设置

$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
$response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
$response->header('Access-Control-Allow-Credentials', 'true');
10 条回复  •  2020-08-14 16:48:38 +08:00
agdhole
   1
agdhole  
   2020 年 8 月 6 日
前后端分离为什么不用 sanctum
xuncanzhe
   2
xuncanzhe  
OP
   2020 年 8 月 6 日
@agdhole 谢谢,刚刚看了一眼功能挺适合的,但是我看最早的版本也用的是 6 版本。请问支持 5 版本么?
agdhole
   3
agdhole  
   2020 年 8 月 6 日
@xuncanzhe #2 应该不支持,而且现在 5.x 有重大的 cookie 漏洞,补丁还未发出 https://learnku.com/laravel/t/47887
lybcyd
   4
lybcyd  
   2020 年 8 月 6 日
Access-Control-Allow-Credentials 设置为 true 的时候,Access-Control-Allow-Origin 不能用*,要设置成具体的地址
xuncanzhe
   5
xuncanzhe  
OP
   2020 年 8 月 14 日
@lybcyd 跨域登录是没问题的,只是刷新完后页面的状态还是未登录。
xuncanzhe
   6
xuncanzhe  
OP
   2020 年 8 月 14 日
@agdhole 再请教一个问题,laravel sanctum 如何从前端传来的 token 来获取用户信息?网上只有配置说明,没找到这个相关的。
agdhole
   7
agdhole  
   2020 年 8 月 14 日
@xuncanzhe #6
中文文档 https://learnku.com/docs/laravel/7.x/sanctum

前端在头把 Authorization 发过去,然后后端用 createToken 方法就行了
agdhole
   8
agdhole  
   2020 年 8 月 14 日
@xuncanzhe #6 获取用户信息可以用 $request->user(); 或者 auth()->user()
https://stackoverflow.com/questions/62941992/getting-user-data-with-laravel-sanctum
xuncanzhe
   9
xuncanzhe  
OP
   2020 年 8 月 14 日
@agdhole 这个我也试过,但是输出是 NULL. 我看请求头里 Authorization 是有相应的 token 的。
```php
Route::get('/getuser', function (Request $request) {
return var_dump( $request->user());
}
```
xuncanzhe
   10
xuncanzhe  
OP
   2020 年 8 月 14 日
@agdhole 谢谢,刚刚试了 Auth::guard('sanctum')->user() 是可以的
© 2026 V2EX · 36ms · 3.9.8.5