【问题标题】:How to disable csrf protection for a route with dynamic parameter?如何为具有动态参数的路由禁用 csrf 保护?
【发布时间】:2023-03-10 18:30:01
【问题描述】:

我有一个在 URL 末尾有一个动态参数的路由。在这条路线中,我使用 post 方法获取从外部 API 发送的数据。由于外部API发送post请求时出现419 page expired错误,我需要为这条路由禁用csrf保护。

相关路线:

Route::group(['middleware' => ['auth:student']], function (){
    Route::post('Result', 'ExamController@Result')->name('exam.Result');
}

我的网址示例:

http://localhost.dev/student/Result?Id=N7utfGkwOLebxMWGA5iUC4S23jgRzW

我尝试将此代码添加到App\Http\MiddlewareVerifyCsrfToken 文件中:

protected $except = [
'student/Result/*',
];

它不起作用。但是当我尝试student/* 时,它运行良好。但是,对所有 student 路径禁用 csrf 保护并不是我想要的。

我也尝试过这种方式,通过this thread 获得参考:

Route::post('Result', [
      'uses' => 'ExamController@Result',
      'nocsrf' => 'true'
    ])->name('exam.Result');

那也没用。

在这种情况下如何禁用 csrf 保护?

【问题讨论】:

    标签: laravel routes csrf


    【解决方案1】:

    试试这个(去掉斜线和星号):

    protected $except = [
    'student/Result',
    ];
    

    【讨论】:

      【解决方案2】:

      您在App\Http\Middleware 打错了字,而不是:

      protected $except = [
      'student/Result/*',
      ];
      

      你需要使用:

      protected $except = [
      'student/Result',
      ];
      

      另外,基于documentation,您可以指定需要排除的完整url:

      protected $except = [
      'http://localhost.dev/student/Result',
      ];
      

      请注意,您不需要在此处添加路由的参数部分(? 符号之后的所有内容,例如 ?Id=N7utfGkwOLebxMWGA5iUC4S23jgRzW)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-19
        • 2021-03-02
        • 2015-03-11
        • 2019-11-12
        • 2015-01-17
        • 2020-12-05
        • 1970-01-01
        • 2019-07-02
        相关资源
        最近更新 更多