How to handle oauth2 and csrf token laravel

☆樱花仙子☆ 提交于 2019-12-25 09:26:11

问题


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

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