Zee*_*Zee 7 php laravel single-page-application vue.js laravel-sanctum
所以已经过了几个小时我无法弄清楚这个问题,即使通读并尝试互联网上可用的任何可能的解决方案。我正在将Laravel 7.x与Vue js一起使用,并在Sanctum SPA身份验证方面苦苦挣扎。
使用web.php 中定义的Auth::routes() 的登录请求工作正常
但是,对auth:sanctum 中间件下api.php 中定义的 API 发出的任何请求都会返回 401。例如,调用获取用户对象失败,状态为 401:
这是请求标头:
这是web.php
这是api.php
这是sanctum.php 中的有状态对象
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1,127.0.0.1:8000')),
在 vue.js 方面,我将 withCredentials 标志设置为 true:
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.withCredentials = true;
在cors.php 中, suports_credentials 标志也设置为 true
而且,这是我的Kernel.php
/**
* The application's route middleware groups.
*
* @var array
*/
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' => [
EnsureFrontendRequestsAreStateful::class,
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
Run Code Online (Sandbox Code Playgroud)
小智 9
我遇到了同样的问题,我找不到任何答案,但在故障排除后我让它工作了。
您的问题是您通过localhost端口 8000访问它,但是在 sanctum config 下的有状态参数中没有localhost:8000(甚至localhost指向127.0.0.1)。配置使用$_SERVER['SERVER_NAME']它实际上在访问它时查找确切的内容。
一个简单的修复如下:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', implode(',', [
'localhost',
'localhost:8000',
]))),
Run Code Online (Sandbox Code Playgroud)
Die*_*tés -2
我不使用 Sanctum,而是使用 Vuejs Laravel 和 Axios,我注意到您需要向所有 axios 受保护的 URL 添加 header Authorization
不记名 YOURTOKENKEY
在我的 ap.js 上我使用
import jwtToken from './helpers/jwt-token'
axios.interceptors.request.use(config => {
config.headers['X-CSRF-TOKEN'] = window.Laravel.csrfToken
config.headers['X-Requested-With'] = 'XMLHttpRequest'
if (jwtToken.getToken()) {
config.headers['Authorization'] = 'Bearer ' + jwtToken.getToken()
}
return config;
}, error => {
return Promise.reject(error);
});
Run Code Online (Sandbox Code Playgroud)
和我的 JWTTOKEN js 文件
export default {
setToken(token) {
window.localStorage.setItem('jwt_token', token);
},
getToken() {
return window.localStorage.getItem('jwt_token');
},
}
Run Code Online (Sandbox Code Playgroud)
因此 axios 的所有请求都会发送带有 Bearer + token 的 Authorization header
我希望这对你有帮助
| 归档时间: |
|
| 查看次数: |
5100 次 |
| 最近记录: |