Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

php - In Laravel 5, How to disable VerifycsrfToken middleware for specific route?

I am using Laravel 5 for developing an app. My app is connected with VendHQ API and I am intended to get some data from VendHQ through their webhook. As per their Documentation

When an event happens and triggers a webhook, we’ll send a POST request to a URL of your choosing. The POST request will be in the UTF-8 charset, and application/x-www-form-urlencoded encoding.

The problem is, when they try to send a POST request to my Laravel app, no CSRF Token is added in their post request and VerifyCsrfToken middleware is looking for a token and finally it throws a TokenMismatchException.

My question is, how can I avoid this default VerifyCsrfToken Middleware for some specific routes while keeping other post requests active?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Laravel 5 this has chagned a bit. Now you can simply add the routes you want to exclude from csrftoken verification, in $except array of the class

'VerifyCsrfToken' (appHttpMiddlewareVerifyCsrfToken.php):

class VerifyCsrfToken extends BaseVerifier
{
    protected $except = [
        // Place your URIs here
    ];
}

Examples:

1. If you are using a route group:

Route::group(array('prefix' => 'api/v2'), function()
{
    Route::post('users/valid','UsersController@valid');
});

Your $except array looks like:

protected $except = ['api/v2/users/valid'];

2. If you are using a simple route

Route::post('users/valid','UsersController@valid');

Your $except array looks like:

protected $except = ['users/valid'];

3. If you want to exclude all routes under main route (users in this case)

Your $except array looks like:

protected $except = ['users/*'];

see: http://laravel.com/docs/master/routing#csrf-excluding-uris


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...