Redirect to a page other than login in Yii 2 behaviors

后端 未结 3 2517
旧时难觅i
旧时难觅i 2021-02-18 18:14

Is there any way to redirect to a page other than login in behaviors method in Yii 2?

My behaviors method content:

public function behaviors()
{
    retu         


        
相关标签:
3条回答
  • 2021-02-18 18:52

    You need to change loginUrl property of yii\web\User class.

    If you want to change it globally, edit your config:

    'components' => [
        'user' => [
            'loginUrl' => ['site/sign-in'],  
        ],
    ],
    

    If you need to change it in the specific controller or action, you can also set it like this:

    Yii::$app->user->loginUrl = ['site/sign-in'];
    

    You need to override beforeAction() method in controller where you need to do this. All access chesks are performed in this event.

    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {
        if (parent::beforeAction($action)) {
            // If you want to change it only in one or few actions, add additional check
    
            Yii::$app->user->loginUrl = ['site/sign-in'];
    
            return true;
        } else {
            return false;
        }
    }
    

    For more details check official documentation about property and event.

    0 讨论(0)
  • 2021-02-18 18:56

    You can benefit from denyCallback(), as Yii2's official document defines it:

    A callback that will be called if the access should be denied to the current user.If not set, denyAccess() will be called.

    The signature of the callback should be as follows:

    function ($rule, $action)
    

    where $rule is the rule that denies the user, and $action is the current action object. $rule can be null if access is denied because none of the rules matched.

    As an example:

    'denyCallback' => function($rule, $action) {
            if ($something) {
                //set flash for example
                Yii::$app->session->setFlash('key', 'Value');
                //Redirect
                return $action->controller->redirect('action');
            }
            //as a default behavior, it throws an exception
            throw new ForbiddenHttpException("Forbidden access");
     },
    
    0 讨论(0)
  • 2021-02-18 18:56

    I'm using yii2-user for user management, and the redirect to login was going to /user/login instead of the yii2-user defined /user/security/login. so my fix was to update the urlManager rules with: '' => 'user/security/'

    I guess this could be used also to redirect to some other controller/action other than login.

    See here.

    0 讨论(0)
提交回复
热议问题