1 回答

TA貢獻1824條經(jīng)驗 獲得超8個贊
成功登錄后,Laravel 使用 AuthenticatesUsers 特征發(fā)送登錄響應(yīng)。
然后,登錄響應(yīng)調(diào)用 session() 上的 regenerate 方法,該方法生成新的 CSRF 令牌。因此,您用于登錄用戶的 csrf 令牌對于下一個 POST 請求不再有效。
/**
* Send the response after the user was authenticated.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
if ($response = $this->authenticated($request, $this->guard()->user())) {
return $response;
}
return $request->wantsJson()
? new Response('', 204)
: redirect()->intended($this->redirectPath());
}
我通過在成功登錄響應(yīng)中返回新的 csrf 令牌來處理此問題,并將其存儲以在下一個 POST 請求中使用。我所說的存儲是指將其作為變量保存在 JavaScript 中,或者在我的例子中使用在應(yīng)用程序狀態(tài)中設(shè)置的 React.js。
在 Auth/LoginController 中,我添加了經(jīng)過身份驗證的方法,該方法覆蓋了 AuthenticatesUsers 特征中的相同方法。
然后,在驗證請求的行之后,我檢查這是否是 Ajax 請求并返回新的 CSRF 令牌。
protected function authenticated(Request $request, $user) {
$credentials = array (
'email' => $request->get('email'),
'password' => $request->get('password'),
);
$valid = Auth::validate($credentials);
if ($valid && $request->ajax()) {
return response()->json([
'auth' => auth()->check(),
'user' => $user,
'intended' => $this->redirectPath(),
'csrf' => csrf_token(),
]);
}
// Nothing changed from here on
}
- 1 回答
- 0 關(guān)注
- 277 瀏覽
添加回答
舉報