Vkal
Vkal

Reputation: 19

How to manually verify CSRF token in Ajax request in Laravel

I am building my first Laravel application and have a problem with the ajax request and specifically the CSRF verification.

I have followed all the steps in the documentation but it is not exactly doing what is said in there.

The App\Http\Middleware\VerifyCsrfToken middleware, which is included in the web middleware group by default, will automatically verify that the token in the request input matches the token stored in the session.

I have been manually concatenating 'test' to all CSRF tokens from the meta tag and the responses is still going through which it shouldn't of course.

Do I now have to manually Verify the CSRF token? If not what's the best practice to verify a token send in the headers of a jquery ajax post request through the controller?

Upvotes: 0

Views: 479

Answers (1)

Tra Lee
Tra Lee

Reputation: 113

I don't really understand what error that you encountered, but here's some Ajax setup and callin that i usually do.

//Setup header before callin ajax
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
//Ajax call update
$.ajax({
    url: '/posts/1/update',
    type: 'POST',
    data: {
        id: 123,
        content: 'Abc123',
    },
    complete: function (response, xhr, settings) {
        //Do something
    }
});

You don't need to edit your VerifyCsrfToken middleware to make this work.

Upvotes: 0

Related Questions