简体   繁体   English

Laravel 4,使用CSRF的filters.php中的令牌不匹配异常

[英]Laravel 4, Token mismatch exception in filters.php using CSRF

I have a problem since 1 week more or less and when I leave open the page of my application but without using it for maybe 4 or 5 hours and return to make a request (a click on a button to load something or things like that) everytime in the console display this: 自从大约1周或更短的时间以来,我一直遇到问题,当我打开应用程序页面,但可能在4或5个小时内没有使用它,然后返回进行请求(单击按钮以加载诸如此类的东西)每次在控制台中显示以下内容:

{
"error":{
    "type":"Illuminate\\Session\\TokenMismatchException",
    "message":"",
    "file":"C:\\xampp182\\htdocs\\mysite\\app\\filters.php",
    "line":97
    }
}

I'm using CSRF protección in my POST request passing for the ajax request this configuration 我在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");
    });

This is my filters.php 这是我的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
    }
});

Edit 编辑

I see the problem, the Session::token() and $token are different but is there a way to regenerate or put the both tokens with the same value? 我看到了问题,Session :: token()和$ token不同,但是有没有办法重新生成或放置两个具有相同值的令牌?

This is how CSRF protection works. 这就是CSRF保护的工作方式。 After session lifetime it generates new token. 在会话生存期之后,它将生成新令牌。 No one normally will fill in the form for 4-5 hours. 通常没有人会在4-5个小时内填写表格。 If you do it just for testing on your localhost you may change lifetime in app/config/session to higher value and it should work. 如果仅在本地主机上进行测试,则可以将app/config/session lifetime更改为更高的值,并且应该可以使用。

Otherwise you may probably change: 否则,您可能会更改:

throw new Illuminate\Session\TokenMismatchException; //Line 97

into something like that 变成这样的东西

 return Redirect:back()->withInput(Input::except('token'))->with('_token',Session::token());

I had this problem on login also. 我在登录时也遇到了这个问题。 From time to time this exception occurred so I stop and tried to reproduce it. 有时会发生此异常,因此我停下来并尝试重现它。 I succeed by doing this: 我这样做是成功的:

First I load the login page. 首先,我加载登录页面。

Then I deleted the cookies. 然后我删除了cookie。

Then, without reloading the login page, I entered username and password and tried to login. 然后,在不重新加载登录页面的情况下,我输入了用户名和密码并尝试登录。

Because session was deleted (when I deleted the cookies), it was normal that this code was not going to pass and it will throw the TokenMismatchException. 因为会话已删除(当我删除cookie时),所以通常不会传递此代码,这将引发TokenMismatchException。

Route::filter('csrf', function() {
    if ( Session::getToken() != Input::get('_token')) {
        throw new Illuminate\Session\TokenMismatchException;
    }
});

So, what I've done to solve my problem was to add a redirect to login page with a message to inform the user that the session might expired. 因此,为了解决问题,我要做的是添加重定向到登录页面,并显示一条消息,通知用户会话可能已过期。

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.');
    }
});

Thus, after page reloading, a new session is created and the problem is solved. 因此,在页面重新加载后,将创建一个新会话并解决该问题。

Simply place the code below into your filters: 只需将下面的代码放入您的过滤器中:

if (Session::token() !== $token)
{
    return Redirect::back()->withInput(Input::except('_token'));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM