简体   繁体   English

如何处理oauth2和csrf令牌Laravel

[英]How to handle oauth2 and csrf token laravel

I installed Laravel 5.2 and oAuth2 Server Laravel in my project. 我在项目中安装了Laravel 5.2和oAuth2 Server Laravel I have to use same function for web-site and web-api. 我必须对网站和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: . 对于网站,我的功能正常运行,但是当我对web-api使用相同的功能时, TokenMismatchException in VerifyCsrfToken.php line 67:显示错误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. 当我将此控制器用于Web时,此代码可以正常工作,但是当我调用API时,此时显示错误。 How I can handle this? 我该如何处理? I have to use oAuth route and web route parallel. 我必须同时使用oAuth路由和网络路由。 Thanks in advance. 提前致谢。

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 您必须对以api开头的路由禁用csrfToken验证,以编辑您的app/Http/Middleware/VerifyCsrfToken.php文件,并在$ except数组中添加api/* (来自laravel应用回购的示例文件)如下

https://github.com/laravel/laravel/blob/5.2/app/Http/Middleware/VerifyCsrfToken.php 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 您还必须从身份验证路由中删除oauth中间件,因为在身份验证期间令牌不可用,因此路由如下所示

Route::group(['prefix'=>'api/'], function()
{
    Route::post('/user/login', 'Auth\AuthController@authenticate');
    Route::group(['middleware' => 'oauth'], function() {
       // routes which needs oauth token verification.
    })

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM