将未授权用户重定向到另一个控制器操作

时间:2016-06-28 09:54:47

标签: yii2

我有登录的控制器代码:

 public function actionLogin()
        {
            if (!\Yii::$app->user->isGuest) {
                return $this->redirect(Yii::$app->request->baseUrl.'/telephone/index'); 
            }

            $model = new LoginForm();
            if ($model->load(Yii::$app->request->post()) && $model->login()) {
                return $this->redirect(Yii::$app->request->baseUrl.'/telephone/index'); 
            }
            return $this->render('login', [
                'model' => $model,
            ]);
        }

为防止我使用的未授权用户adddelete操作:

public function behaviors()
{
    return [
            'access' => [
            'class' => AccessControl::className(),
            'only' => ['add','delete'],
            'rules' => [
                // allow authenticated users
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
                // everything else is denied by default
            ],
        ],
    ];
}

但是,如果未经授权的用户clik添加或删除,则会将其重定向到site/login。如何更改控制器和操作?

2 个答案:

答案 0 :(得分:3)

根据范围,有不同的方法来更改该路线。它们都涉及更改loginUrl类的yii\web\User属性。

<强>全球

编辑配置文件。

'components' => [
    'user' => [
        'loginUrl' => ["controller/action"],  
    ],
],

<强>控制器/动作

编辑控制器的beforeAction方法。

public function beforeAction($action)
{
    // action-specific
    if(in_array($action->id,['not', 'allowed', 'actions']))
        Yii::$app->user->loginUrl = ["controller/action"];

    // controller-wide
    Yii::$app->user->loginUrl = ["controller/action"];

    if (!parent::beforeAction($action)) {
        return false;
    }

    return true;
}

答案 1 :(得分:-1)

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['add','delete'],
            'rules' => [
                'allow' => true,
                'actions' => ['add','delete'],
                'roles' => ['@'],
                'denyCallback' => function ($rule, $action) {
                    return $this->redirect('index.php?r=site/login');
                }
            ],
        ],
    ];
}