在 Yii2 中禁用单个操作的 CSRF 验证 [英] Disable CSRF validation for individual actions in Yii2

查看:20
本文介绍了在 Yii2 中禁用单个操作的 CSRF 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法为控制器的某些操作禁用 CSRF 验证,并为其他操作启用它?

Is there a way to disable CSRF validation for some actions of the controller keeping it enabled for the other ones?

就我而言,我有几个可配置的 Action 类,它们旨在注入控制器.我无法将 csrf 验证令牌传递到 AJAX 请求中,因为我正在使用的东西是前端的外部(不是我制作的)WYSIWYG 插件.是的,我仍然可以使用这些操作禁用整个控制器的 csrf 验证,但它可能不安全.

In my case I have several configurable Action classes, that are intended to be injected into controllers. I can't pass csrf validation token into the AJAX request because the thing I'm working with is external (made not by me) WYSIWYG plugin at the frontend. Yes, I can still disable csrf validation of the whole controller using these actions, but it may be insecure.

推荐答案

对于特定的控制器/动作,您可以像这样禁用 CSRF 验证:

For the specific controller / actions you can disable CSRF validation like so:

use Yii;

...

Yii::$app->controller->enableCsrfValidation = false;

或者在控制器内部:

$this->enableCsrfValidation = false;

查看 $enableCsrfValidation 属性 yiiwebController.

更新:

这是一些规范.

如果您想禁用单个操作的 CSRF 验证,您需要在 beforeAction 事件处理程序中执行此操作,因为在操作运行之前检查 CSRF 令牌(在 beforeAction 中)yiiwebController).

If you want to disable CSRF validation for individual action(s) you need to do it in beforeAction event handler because CSRF token is checked before action runs (in beforeAction of yiiwebController).

/**
 * @inheritdoc
 */
public function beforeAction($action)
{            
    if ($action->id == 'my-method') {
        $this->enableCsrfValidation = false;
    }

    return parent::beforeAction($action);
}

官方文档:

这篇关于在 Yii2 中禁用单个操作的 CSRF 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆