使用 REST API 保护 Laravel CSRF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37133475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:45:24  来源:igfitidea点击:

Laravel CSRF protection with REST API

apirestlaravelcsrf

提问by Vijayanand Premnath

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. How to solve this?

当我测试我的 RESTful API 层时,我收到令牌不匹配错误。如何解决这个问题?

I use CSRF protection for regular form submissions a user might do. But how would that work for an API? I have my API calls grouped after my regular routes as below

我将 CSRF 保护用于用户可能执行的常规表单提交。但这对 API 有何作用?我的 API 调用按常规路线分组,如下所示

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

回答by Achraf Khouadja

In your App\Http\Middleware\VerifyCsrfToken

在你的 App\Http\Middleware\VerifyCsrfToken

you will have such a class, add your routes to the $except

您将拥有这样一个课程,将您的路线添加到 $except

namespace App\Http\Middleware;

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

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

回答by Giedrius Kir?ys

You should consider using different middleware groups for Your web and api layers. Laravel by default, depending on version You are using, uses webmiddleware group.

您应该考虑为您的 web 和 api 层使用不同的中间件组。Laravel 默认情况下,根据您使用的版本,使用web中间件组。

If You are not having line like this Route::group(['middleware' => 'web'], function () {in Your routes.phpfile, then Your laravel version is that one which uses it by default. Check Your RouteServiceProvider.phpfile 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. Then use webmiddleware for part where You need sessions, csrf and other stuff, and use apimiddleware where You don't need these things (apimiddleware group does not include sessions, encrypted cookies and csrf verifications).

如果出现,请'middleware' => 'web'routes.php. 然后web在需要会话、csrf 和其他东西的部分使用api中间件,在不需要这些东西的地方使用中间件(api中间件组不包括会话、加密的 cookie 和 csrf 验证)。