dhanashri dhanashri - 1 year ago 105
PHP Question

How to handle oauth2 and csrf token laravel

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.

Sam Sam
Answer Source

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


just make it something like

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 = [

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download