问题
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