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

查看:184
本文介绍了对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 属性的 yii\web\Controller

更新:

这是一些规范。

如果您想对单个操作禁用CSRF验证,则需要在 beforeAction 事件处理程序,因为在操作运行之前已检查CSRF令牌(在 yii\web\Controller beforeAction 中$ c>)。

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 yii\web\Controller).

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

    return parent::beforeAction($action);
}

官方文档:

  • beforeAction()

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

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