我正在用 Vue 构建一个 SPA。我的前端和后端(Laravel)在同一个代码库中。我想通过 Laravel Passport Middleware CreateFreshApiToken访问我的 API(在我的后端)。我正在通过web.php在我的AuthController中接近我的登录方法。
我的问题: 一旦我通过登录方法成功登录,我希望此时 Passport 创建laravel_token cookie。不是这种情况。cookie 是在页面刷新后创建的。但正如我所说,我正在构建一个 SPA,这就是我不想刷新页面的原因。
我想要什么: 我想通过我的登录方法登录,然后使用 Passport CreateFreshApiToken中间件。之后,我想使用(刚刚在中间件中创建的)laravel_token cookie,以便我可以在 SPA 的登录部分中正确安全地与我自己的 API 对话。
更多信息:
内核.php
// Code...
protected $middlewareGroups = [
'web' => [
// other middlewares...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
];
// Code...
AuthController.php
// Code...
public function login()
{
if (Auth::attempt(['email' => Input::get('email'), 'password' => Input::get('password')], true)) {
return response()->json([
'user' => Auth::user(),
'authenticated' => auth()->check(),
]);
}
return response()->json(['authenticated' => false], 401);
}
// Code...
登录.vue
// Code...
methods: {
login: function (event) {
event.preventDefault();
this.$http.post(BASE_URL + '/login', {
email: this.email,
password: this.password,
})
.then(function (response) {
localStorage.user_id = response.body.user.id;
router.push({
name: 'home'
});
});
},
},
// Code...
出了什么问题?这个:
CreateFreshApiToken.php
// Code...
public function handle($request, Closure $next, $guard = null)
{
$this->guard = $guard;
$response = $next($request);
// I'm signed in at this point
if ($this->shouldReceiveFreshToken($request, $response)) { // returns false unless you refresh the page. That's why it won't create the laravel_token cookie
$response->withCookie($this->cookieFactory->make(
$request->user($this->guard)->getKey(), $request->session()->token()
));
}
return $response;
}
protected function shouldReceiveFreshToken($request, $response)
{
// both methods below return false
return $this->requestShouldReceiveFreshToken($request) &&
$this->responseShouldReceiveFreshToken($response);
}
protected function requestShouldReceiveFreshToken($request)
{
// $request->isMethod('GET') - returns false because it's a POST request
// $request->user($this->guard) - returns true as expected
return $request->isMethod('GET') && $request->user($this->guard);
}
protected function responseShouldReceiveFreshToken($response)
{
// $response instanceof Response - returns false
// ! $this->alreadyContainsToken($response) - returns false as expected
return $response instanceof Response &&
! $this->alreadyContainsToken($response);
}
// Code...
我认为我想要实现的目标是可能的吗?如果是,如何?