Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

E-dreamz_TP's avatar

L5 : TokenMismatchException With Ajax Post

I am doing an ajax post with jQuery and getting a TokenMismatchException Error. I assume I have to pass the token with the post. Has anyone ran into this?

0 likes
8 replies
vjacob's avatar

In your app/Http/Middleware/VerifyCsrfToken.php, change the tokenMatch() method to this.

/**
 * Determine if the session and input CSRF tokens match.
 *
 * @param \Illuminate\Http\Request $request
 * @return bool
 */
protected function tokensMatch($request)
{
    // If request is an ajax request, then check to see if token matches token provider in
    // the header. This way, we can use CSRF protection in ajax requests also.
    $token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');

    return $request->session()->token() == $token;
}

Then in your javascript file (assuming you are using jQuery), do this

// CSRF protection
$.ajaxSetup(
{
    headers:
    {
        'X-CSRF-Token': $('input[name="_token"]').val()
    }
});

This will allow us to pass the csrf token as a header with the ajax request. The middleware will check to see if the token matches the header.

7 likes
jfranc014's avatar

Hi, I have two questions regarding this fact: The final L5 release has already included the verification suggested by @vjacob,hasn't it? If working with angular.js would the same approach apply to handle ajax requests? Thanks!

nolros's avatar

Pretty much the same

var getToken = function(){
        return $('#mme-token').prop('value');
};

You would have some AJS method that then uses submits the token. I'm not including the AJS service provider for brevity sake.

    $scope.add = function() {

        var token = getToken();

        if(! isBlankOrEmpty(token)) {
            $scope.d._token = token;
        } else {
            $scope.isFormValid = false;
            throw "Form verification valid!! Please stop and login!";
        }

            FormService.add($scope.d)
                .success(function(d, status) {

                })
                .error(function() {

                });


    };
Shirley's avatar

You can add the urls that sould be exluded from CSRF verification in class VerifyCsrfToken (App\Http\Middleware).

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'url'
    ];
}
2 likes
ienderli's avatar

I have had good luck fetching and setting a XSRF-TOKEN from the cookie that Laravel sets. I am not quite sure how angular does it, but the examples below have worked for me using jQuery and Vue. Also, make sure you're setting the token in the browser. Most commonly done by placing your routes inside the web middleware group.

Route::group(['middleware' => ['web']], function () {
         // Homepage
         Route::get('/', ['as' => 'home', 'uses' => 'PagesController@home']);
    // More awesome routes.....
});

Now on to the javascript side...

var getXsrfToken = function() {
    var cookies = document.cookie.split(';');
    var token = '';

    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i].split('=');
        if(cookie[0] == 'XSRF-TOKEN') {
            token = decodeURIComponent(cookie[1]);
        }
    }

    return token;
}

Then with jQuery you can do

jQuery.ajaxSetup({
    headers: {
        'X-XSRF-TOKEN': getXsrfToken()
    }
});

and when using vue-resource

    Vue.http.headers.common['X-XSRF-TOKEN'] = getXsrfToken()
1 like
rmff's avatar

I have found (on web) a nice solution, without evolving change the middleware.

Simple insert a META tag on the page where you will do the Ajax request and default middleware will check for csrf_token.

Works on L5.2

1 like

Please or to participate in this conversation.