VerifyCsrfToken always called when route to API Middleware Laravel 5.2.35

时光毁灭记忆、已成空白 提交于 2019-12-11 04:58:25

问题


I have two similiar Laravel project. This is part code of kernel.php. Both projects have same code.

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],
    'api' => [
        'throttle:60,1',
    ],
];

But, VerifyCsrfToken always be called although I put my route inside api middlewareGroup.

I check request header in Advanced REST Client. I found this.

First project result :

Second project result :

First result has cookie attribute in request header, but second result doesn't have


回答1:


All the routes in routes.php are included in a route group which has the 'web' middleware applied. You should probably create another routes file and have the RouteServiceProvider load those in a group with 'api' and without the 'web' middleware applied.

If you open up your RouteServiceProvider you will see where this is happening. Check the map method to see it calling mapWebRoutes.




回答2:


Use routes without any middleware and it will not require csrf token anymore.




回答3:


You can skip csrf token check for all your api links in app/Http/Middleware/VerifyCsrfToken.php by adding the URIs to the $except property. Example:

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


来源:https://stackoverflow.com/questions/37548785/verifycsrftoken-always-called-when-route-to-api-middleware-laravel-5-2-35

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!