问题
I installed Laravel 5.2 and oAuth2 Server Laravel
in my project. I have to use same function for web-site and web-api. For web-site my function is working properly but when I use same function for web-api shown error TokenMismatchException in VerifyCsrfToken.php line 67:.
My Route
/* for web*/
Route::post('admin/user_login', 'Auth\AuthController@authenticate');
/* for mobile api */
Route::group(['prefix'=>'api/','before' => 'oauth'], function()
{
Route::post('/user/login', 'Auth\AuthController@authenticate');
});
When I use this controller for web, this code working fine but when I call API that time shown error. How I can handle this? I have to use oAuth route and web route parallel. Thanks in advance.
回答1:
you have to disable csrfToken verification for routes starting with api to do that edit your app/Http/Middleware/VerifyCsrfToken.php file and add api/* in the $except array the sample file from laravel app repo is as below
https://github.com/laravel/laravel/blob/5.2/app/Http/Middleware/VerifyCsrfToken.php
just make it something like
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'api/*'
];
}
also you have to remove oauth middleware from authenticate route, because during authentication the token is not available so route goes something like below
Route::group(['prefix'=>'api/'], function()
{
Route::post('/user/login', 'Auth\AuthController@authenticate');
Route::group(['middleware' => 'oauth'], function() {
// routes which needs oauth token verification.
})
});
来源:https://stackoverflow.com/questions/40910190/how-to-handle-oauth2-and-csrf-token-laravel