php 为什么 Laravel API 在 POST 和 PUT 方法上返回 419 状态代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46266553/
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-08-26 03:12:20  来源:igfitidea点击:

Why does the Laravel API return a 419 status code on POST and PUT methods?

phprestlaravel-5

提问by Navid_pdp11

I am trying to create a RESTful API by using Laravel. I have created my controller using php artisan make:controller RestControllerand this is my controller code:

我正在尝试使用 Laravel 创建一个 RESTful API。我已经使用php artisan make:controller RestController创建了我的控制器,这是我的控制器代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class RestController extends Controller
{
    private $arr = array(
            array("name"=>"jon", "family"=>"doe"),
            array("name"=>"jhon", "family" => "doue")
        );
    public function index(){
        return json_encode($this->arr);
    }

    public function store(Request $request){
        return "oops!!";
    }

    public function update (Request $request, $id){
        return "test";
    }

}

I have added this line of code to create this route in my routes/web.php file:

我已经添加了这行代码来在我的 routes/web.php 文件中创建这个路由:

Route::resource('person', 'RestController');

When I try to test this api on GET /person it works fine but on POST and PUT I am getting a 419 status code from Laravel.

当我尝试在 GET /person 上测试此 api 时,它工作正常,但在 POST 和 PUT 上,我从 Laravel 获得了 419 状态代码。

回答by iCoders

if you are developing rest apis better not to add token .if you are using 5.4 or 5.5 you can use api.php instead of web.php .In api.php you dont need token verifcation on post request.

如果您正在开发 rest apis 最好不要添加令牌。如果您使用 5.4 或 5.5,您可以使用 api.php 而不是 web.php 。在 api.php 中,您不需要在发布请求时进行令牌验证。

if you are using web.php then you exculde token .Here is the official documentation

如果您使用的是 web.php,那么您排除令牌。这是官方文档

Excluding URIs From CSRF Protection

从 CSRF 保护中排除 URI

Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.

有时您可能希望从 CSRF 保护中排除一组 URI。例如,如果您使用 Stripe 处理付款并使用他们的 webhook 系统,您将需要从 CSRF 保护中排除您的 Stripe webhook 处理程序路由,因为 Stripe 不知道要向您的路由发送什么 CSRF 令牌。

Typically, you should place these kinds of routes outside of the web middleware group that the RouteServiceProvider applies to all routes in the routes/web.php file. However, you may also exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware:

通常,您应该将这些类型的路由放置在 RouteServiceProvider 应用于 routes/web.php 文件中的所有路由的 Web 中间件组之外。但是,您也可以通过将路由的 URI 添加到 VerifyCsrfToken 中间件的 $except 属性来排除路由:

<?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 = [
        'stripe/*',
    ];
}

for reference

以供参考

https://laravel.com/docs/5.5/csrf

https://laravel.com/docs/5.5/csrf

回答by Puneet Verma

As per my Knowledge there are two methods to solve this

根据我的知识,有两种方法可以解决这个问题

Method-1:- Add CsrF Token

方法 1:- 添加 CsrF 令牌

Method-2:- Exclude URIs from CSRF protection

方法 2:- 从 CSRF 保护中排除 URI

How to use

如何使用

Method-1:- Add one more variable to your POST request.

方法 1:- 在 POST 请求中再添加一个变量。

"_token": "{{ csrf_token() }}"

Example for Ajax

Ajax 示例

 req = $.ajax({
    type: "POST",
    url: "/search",
    data: {'key' : 'value',
    "_token": "{{ csrf_token() }}",},
    dataType: "text",
    success: function(msg){

    }
});

Example if you using forms

使用表单的示例

<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">

Method-2 There is a file named 'VerifyCsrfToken' in following location

方法 2 在以下位置有一个名为“VerifyCsrfToken”的文件

yourProjectDirectory --> app->Http--> Middleware

Add your URL in following method

在以下方法中添加您的网址

 protected $except = [

            'url1/',
            'url2/',

 ];

When To use

何时使用

  • If you are the owner(full control) of API, use Method 1, as CSRF TOKEN adds security to your application.

  • If you are unable to add CSRF token like in case if you are using any third party API's, webhooks etc go for Method-2.

  • 如果您是 API 的所有者(完全控制),请使用方法 1,因为 CSRF TOKEN 为您的应用程序增加了安全性。

  • 如果您无法添加 CSRF 令牌,例如在使用任何第三方 API、webhooks 等的情况下,请使用 Method-2。

回答by Ali Motameni

I solved this problem by changing my server cachesetting. You can disable all of your caching systems (Nginx, Cloudflare, ...) to check it and then turn it on by applying QueryString + Cookieto prevent caching a page with old csrf tokenin it.

我通过更改服务器缓存设置解决了这个问题。您可以禁用所有缓存系统(Nginx、Cloudflare 等)来检查它,然后通过应用将其打开QueryString + Cookie以防止缓存包含旧的页面csrf token