laravel - CSRF token always changes

感情迁移 提交于 2019-12-02 01:12:57

问题


Well this is the problem I am facing from yesterday. It is always giving me TokenMismatchException and when I digged in and compared a few things, I found that on my local server, the _token field never changes. But on my production, it does. And that's the reason it kept giving me TokenMismatchException. Does anyone know how to fix this error.

I have

  1. seen this question
  2. Went through documentation.
  3. Wrote several codeception tests.
  4. <input id="token" type="hidden" value="{{ csrf_token() }}"> this already in my code.

回答1:


Check if you have domain in the config/session.php setup to the right path. Even I had got the same problem. And resolved it just by changing that path.




回答2:


May be usefull.

Html:

<meta name="_token" content="{{ csrf_token() }}">

Js:

var network = {
    post: function(path, params, cb, type){
        $.ajax({
            url: path,
            type: 'post',
            data: params,
            headers: { "X-CSRF-TOKEN" : $('meta[name="_token"]').attr('content') },
            dataType: type,
            success: function (response, status) {
                if (status == "success") {
                    if (response.reason == "token_timeout") {
                        var new_token = response.new_token;
                        $('meta[name="_token"]').attr('content', new_token);
                        network.post(path, params, cb, type);
                    }else{
                        cb(response);
                    }
                }
            }
        });
    }
};

network.post('path to handler...', { key: value... }, function(response){
   if(response.status == 'success'){
       // to do
   }
}, "json");

/app/Exceptions/Handler.php:

    public function render($request, Exception $exception) {

        if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
            return response()->json(['reason' => 'token_timeout', 'new_token' => csrf_token()], 200);
        }

        return parent::render($request, $exception);
    }


来源:https://stackoverflow.com/questions/30499344/laravel-csrf-token-always-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!