-->

How to allow guest access to some actions in Yii2

2019-07-13 03:11发布

问题:

I'd like to know how to configure my controller to allow some actions to be executed as a guest and be able to show the view for that guest in Yii2.

I've tried this rule in my behaviour

       'access' => [
           'class' => AccessControl::className(),                           
                'rules' => [
                    [                   
                        'actions' => ['create','update'],       
                        'allow' => true,
                        'ips' => ['127.0.0.1'],                         
                    ]                       
                ],                  
            ]

Edit: This is the config I tried :

    'access' => [
                'class' => AccessControl::className(),                          
                'rules' => [                                
                    [
                        'allow' => true,
                        'actions' => ['create', 'update'],
                        'roles' => ['?'],
                    ],
                ],                  
            ]

Edit2: After checking out a new project(yii2-advanced) from scratch and trying to generate the controllers and models again the previous rules worked, I think it was some configuration from the previous project that were preventing me to access as a guest somehow.

回答1:

In your rules

                [
                    'allow' => true,
                    'actions' => ['login', 'signup'],
                    'roles' => ['?'],
                ],

Then the actions login and signup will be allowed for anonymous users.

Or you can use the only method also, to exempt the action which does not require acl.

For more details,see http://www.yiiframework.com/doc-2.0/guide-security-authorization.html