Laravel 5.3 POST and tokenmismatch

2019-07-28 16:30发布

问题:

I have a page that I want to have a POST sent to which will trigger a database update. The request will come from another site.

Route::post('update', 'DatabaseController@update');

The request includes a single element

(raw)

id=12345

(form-data)

id: 12345

Whenever I access the page, I get this error

TokenMismatchException in VerifyCsrfToken.php line 68:

回答1:

Laravel makes it easy to protect your application from cross-site request forgery (CSRF) attacks. Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are performed on behalf of an authenticated user.

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application.

Anytime you define a HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware can validate the request. You may use the csrf_field helper to generate the token field:

<form method="POST" action="/profile">
    {{ csrf_field() }}
    ...
</form>

In addition to checking for the CSRF token as a POST parameter, the VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could, for example, store the token in a HTML meta tag:

<meta name="csrf-token" content="{{ csrf_token() }}">

Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

Reference

Note: To exclude some URI's from CSRF verification go to project/app/Http/Middleware, open the file VerifyCsrfToken.php and pass your url like:

protected $except = [
    '/api/authuser',
];

the url passed in this array are excluded from URI's from CSRF verification.