Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSRF Token Mismatch | Laravel 5.4

Tags:

php

laravel

Whenever I send a POST request to server, TokenMismatchException error comes. I have already tried sending

<input type="hidden" name="_token" value= "{{csrf_token()}}">

Earlier, I was using ajaxHeader to send this particular piece of information to server but that is also throwing same error.

I have debugged more and find out that in VerifyCsrfToken file.

protected function tokensMatch($request)
    {
        $token = $this->getTokenFromRequest($request);
        return is_string($request->session()->token()) &&
               is_string($token) &&
               hash_equals($request->session()->token(), $token);
    } 

array:3 [
 "sessionToken" => "rgicYLOUhb2kLLChpVByNLQO1KVMb0Gkjzb7ZtTN" //$request->session()->token()
 "requestToken" => "IgXWquvnfujZJ1Vs9vbSgpjgX3rAnd5PpeklRvBD"  // $request->input('_token') ?: $request->header('X-CSRF-TOKEN')
 "laravel_token" => "rgicYLOUhb2kLLChpVByNLQO1KVMb0Gkjzb7ZtTN" //csrf_token()
]

I am getting above array in middleware token match function. Can anybody please tell me the reason and solution of this particular problem ? Below is the ajax I am using

function likeReview(id)
    {
        var like_span = $('#like_'+id);
        var like_div  = $('#likeDiv_'+id);
        var like_span_text = $('#likeText_'+id);
        $.ajax({
            type: 'post',
            url: '{{route('like.review')}}',
            data: {review_id: id},
            beforeSend: function () {
            },
            success: function (data) {
                if(data.status == 'success')
                {
                    var like = like_span.html();
                    var sum  = 0;
                    if(data.like == 1){
                        sum = parseInt(like)+1;
                        like_div.addClass('upvoted-active');
                        like_span_text.html('UPVOTED');
                    } else {
                        sum = parseInt(like)-1;
                        like_div.removeClass('upvoted-active');
                        like_span_text.html('UPVOTE');
                    }
                    like_span.html(sum);
                }
            },
            error: function (xhr, textStatus, thrownError) {
                alert('Something went wrong. Please try again!');
            }
        });
    }

Function is called on click of upvote button

<div class="js-btn-thank-area upvoted-active js-activity-root" id="likeDiv_{{$review->id}}">
    <a href="javascript:;" onclick="likeReview({{$review->id}})" class="thank-btn">
    <i class="fa fa-arrow-up fa-fw"></i>
    <span class="feed-action-text" id="likeText_{{$review->id}}">UPVOTED</span>
   </a>
   <div class="stats-thanks" id="like_{{$review->id}}">                                                                    
    {{$review->likes()->where('like','=',1)->count()}}
   </div>
 </div>
like image 505
Shwetank Avatar asked May 08 '17 07:05

Shwetank


People also ask

How do I enable CSRF cookies in Chrome?

Open Chrome Settings. In the Privacy and security section, click Cookies and other site data. Scroll down to Sites that can always use cookies and click Add.

How do I get my CSRF token?

To fetch a CRSF token, the app must send a request header called X-CSRF-Token with the value fetch in this call. The server generates a token, stores it in the user's session table, and sends the value in the X-CSRF-Token HTTP response header.

What does CSRF token mismatch mean?

This error message means that your browser couldn't create a secure cookie, or couldn't access that cookie to authorize your login. This can be caused by ad- or script-blocking plugins, but also by the browser itself if it's not allowed to set cookies.


1 Answers

Just using CSRF as a field for posting with AJAX does not work;

$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });

Before you make the ajax call set it up :)!

EDIT: You can also put in the data part of your ajax request;

data: {
    review_id: id,
    "_token": "{{ csrf_token() }}"
}

EDIT: To clarify clearing temporary data from storage solved this issue in chat.

like image 130
Robert Pounder Avatar answered Sep 17 '22 17:09

Robert Pounder