简体   繁体   English

使用REST API进行Laravel CSRF保护

[英]Laravel CSRF protection with REST API

I have this code at the top of my routes file 我在路由文件的顶部有这个代码

Route::when('*', 'csrf', array('post', 'put', 'delete'));

When I testing my RESTful API layer I get token mismatch error. 当我测试我的RESTful API层时,我得到令牌不匹配错误。 How to solve this? 怎么解决这个?

I use CSRF protection for regular form submissions a user might do. 我将CSRF保护用于用户可能执行的常规表单提交。 But how would that work for an API? 但是如何为API工作呢? I have my API calls grouped after my regular routes as below 我的API调用按照常规路由分组,如下所示

Route::group(array('prefix' => 'api'), function () {
Route::resource('shows', 'ShowsApiController');
Route::resource('episode', 'EpisodesApiController');
Route::resource('genre', 'GenresApiController');
});

In your App\\Http\\Middleware\\VerifyCsrfToken 在您的App\\Http\\Middleware\\VerifyCsrfToken

you will have such a class, add your routes to the $except 你将有这样一个班级,将你的路线添加到$除外

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
  protected $except = [
    'shows/*',
    'episode/*',
    'genre/*',
  ];
}

You should consider using different middleware groups for Your web and api layers. 您应该考虑为Web和api层使用不同的中间件组。 Laravel by default, depending on version You are using, uses web middleware group. 默认情况下,Laravel根据您使用的版本使用web中间件组。

If You are not having line like this Route::group(['middleware' => 'web'], function () { in Your routes.php file, then Your laravel version is that one which uses it by default. Check Your RouteServiceProvider.php file for this line: https://github.com/laravel/laravel/blob/master/app/Providers/RouteServiceProvider.php#L56 . 如果你是不是有一行这样的Route::group(['middleware' => 'web'], function () {在你的routes.php的文件,然后你laravel版本是一个在默认情况下使用它。检查你的此行的RouteServiceProvider.php文件: https//github.com/laravel/laravel/blob/master/app/Providers/RouteServiceProvider.php#L56

If presented, remove 'middleware' => 'web' part and group routes Yourself in routes.php . 如果出现,删除'middleware' => 'web'部分并在routes.php分组你自己。 Then use web middleware for part where You need sessions, csrf and other stuff, and use api middleware where You don't need these things ( api middleware group does not include sessions, encrypted cookies and csrf verifications). 然后将web中间件用于需要会话,csrf和其他内容的部分,并使用api中间件,其中您不需要这些东西( api中间件组不包括会话,加密cookie和csrf验证)。

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

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