Laravel 5.4 护照 axios 总是 returns 未经身份验证
Laravel 5.4 passport axios always returns Unauthenticated
我已按照此处的指南进行操作:https://laravel.com/docs/5.4/passport#consuming-your-api-with-javascript
使用 axios:
...
mounted: function() {
axios.get('/api/user')
.then(function (response) {
console.log(response)
})
.catch(function (response) {
console.error(response);
});
},
但响应始终未经身份验证,我检查是否存在 laravel_token cookie,它是:
我 运行 在 apache2 ( docker )
----更新--
调试后,实际上是 TokenGuard
中此方法失败的 xsrf 令牌:
/**
* Authenticate the incoming request via the token cookie.
*
* @param Request $request
* @return mixed
*/
protected function authenticateViaCookie($request)
{
try {
$token = $this->decodeJwtTokenCookie($request);
} catch (Exception $e) {
return;
}
# This is not passing:
if (! $this->validCsrf($token, $request) ||
time() >= $token['expiry']) {
return;
}
if ($user = $this->provider->retrieveById($token['sub'])) {
return $user->withAccessToken(new TransientToken);
}
}
我在 boostrap.js 中有适当的设置:
window.axios = require('axios');
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest'
};
这实际上是一个 Laravel / 文档问题。
passport token guard 正在寻找 X-CSRF-TOKEN
,但 axios 发送 X-XSRF-TOKEN
。将您的 axios 配置更改为:
window.axios.defaults.headers.common = {
'X-CSRF-TOKEN': window.Laravel.csrfToken,
'X-Requested-With': 'XMLHttpRequest'
};
我打开了一个 PR,这应该是未来 Laravel 版本的默认设置。
我已按照此处的指南进行操作:https://laravel.com/docs/5.4/passport#consuming-your-api-with-javascript
使用 axios:
...
mounted: function() {
axios.get('/api/user')
.then(function (response) {
console.log(response)
})
.catch(function (response) {
console.error(response);
});
},
但响应始终未经身份验证,我检查是否存在 laravel_token cookie,它是:
我 运行 在 apache2 ( docker )
----更新--
调试后,实际上是 TokenGuard
中此方法失败的 xsrf 令牌:
/**
* Authenticate the incoming request via the token cookie.
*
* @param Request $request
* @return mixed
*/
protected function authenticateViaCookie($request)
{
try {
$token = $this->decodeJwtTokenCookie($request);
} catch (Exception $e) {
return;
}
# This is not passing:
if (! $this->validCsrf($token, $request) ||
time() >= $token['expiry']) {
return;
}
if ($user = $this->provider->retrieveById($token['sub'])) {
return $user->withAccessToken(new TransientToken);
}
}
我在 boostrap.js 中有适当的设置:
window.axios = require('axios');
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest'
};
这实际上是一个 Laravel / 文档问题。
passport token guard 正在寻找 X-CSRF-TOKEN
,但 axios 发送 X-XSRF-TOKEN
。将您的 axios 配置更改为:
window.axios.defaults.headers.common = {
'X-CSRF-TOKEN': window.Laravel.csrfToken,
'X-Requested-With': 'XMLHttpRequest'
};
我打开了一个 PR,这应该是未来 Laravel 版本的默认设置。