[英]Unable to migrate the filters.php file from laravel 4 to laravel 5
[英]Laravel 4, Token mismatch exception in filters.php using CSRF
自從大約1周或更短的時間以來,我一直遇到問題,當我打開應用程序頁面,但可能在4或5個小時內沒有使用它,然后返回進行請求(單擊按鈕以加載諸如此類的東西)每次在控制台中顯示以下內容:
{
"error":{
"type":"Illuminate\\Session\\TokenMismatchException",
"message":"",
"file":"C:\\xampp182\\htdocs\\mysite\\app\\filters.php",
"line":97
}
}
我在POST請求傳遞的ajax請求中使用CSRFprotección配置此配置
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
這是我的filters.php
/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function($route, $request)
{
if (strtoupper($request->getMethod()) === 'GET')
{
return; // get requests are not CSRF protected
}
$token = Request::ajax() ? Request::header('x-csrf-token') : Input::get('_token');
if (Session::token() != $token)
{
throw new Illuminate\Session\TokenMismatchException; //Line 97
}
});
編輯
我看到了問題,Session :: token()和$ token不同,但是有沒有辦法重新生成或放置兩個具有相同值的令牌?
這就是CSRF保護的工作方式。 在會話生存期之后,它將生成新令牌。 通常沒有人會在4-5個小時內填寫表格。 如果僅在本地主機上進行測試,則可以將app/config/session
lifetime
更改為更高的值,並且應該可以使用。
否則,您可能會更改:
throw new Illuminate\Session\TokenMismatchException; //Line 97
變成這樣的東西
return Redirect:back()->withInput(Input::except('token'))->with('_token',Session::token());
我在登錄時也遇到了這個問題。 有時會發生此異常,因此我停下來並嘗試重現它。 我這樣做是成功的:
首先,我加載登錄頁面。
然后我刪除了cookie。
然后,在不重新加載登錄頁面的情況下,我輸入了用戶名和密碼並嘗試登錄。
因為會話已刪除(當我刪除cookie時),所以通常不會傳遞此代碼,這將引發TokenMismatchException。
Route::filter('csrf', function() {
if ( Session::getToken() != Input::get('_token')) {
throw new Illuminate\Session\TokenMismatchException;
}
});
因此,為了解決問題,我要做的是添加重定向到登錄頁面,並顯示一條消息,通知用戶會話可能已過期。
Route::filter('csrf', function() {
if ( Session::getToken() != Input::get('_token')) {
return Redirect::to('/admin/login')->with('warning', 'Your session has expired. Please try logging in again.');
}
});
因此,在頁面重新加載后,將創建一個新會話並解決該問題。
只需將下面的代碼放入您的過濾器中:
if (Session::token() !== $token)
{
return Redirect::back()->withInput(Input::except('_token'));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.