All Yii2 controller not allow action without login

2020-04-20 23:33发布

I'm using Yii2 Advance application and i am new in yii2 so how make

all yii2 controller not allow action without login or guest must me login

i mean controllers can not open without login if user not login so redirect in login page this not for one controller i need many controller

标签: yii2
4条回答
孤傲高冷的网名
2楼-- · 2020-04-21 00:03

You could simply create a super controller for this :

class Controller extends \yii\web\Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => false,
                        'roles' => ['?'],
                    ],
                ],
            ],
        ];
    }
}

And of course all your controllers should extend this one.

Read more about Access Control Filter.

查看更多
贼婆χ
3楼-- · 2020-04-21 00:06

You need to add below code in common/main.php after components part.

'as beforeRequest' => [  //if guest user access site so, redirect to login page.
        'class' => 'yii\filters\AccessControl',
        'rules' => [
            [
                'actions' => ['login', 'error'],
                'allow' => true,
            ],
            [
                'allow' => true,
                'roles' => ['@'],
            ],
        ],
    ],
查看更多
劫难
4楼-- · 2020-04-21 00:18

use RBAC Manager for Yii 2 you can Easy to manage authorization of user. https://github.com/mdmsoft/yii2-admin.

查看更多
Viruses.
5楼-- · 2020-04-21 00:23

You could inherit from the yii Controller class where you can override the beforeAction method and in that function you can redirect the user if there is no active logged in session. Make sure that all of the other controllers what you are using inherited from your new controller class.

EDIT:

In the SuperController beforeAction you can check if the current call is your site/index, if not then redirect to there like:

if($action->controller != "site" && $action->id != "index" ) {
  $this->goHome();
}

Make sure that the goHome() take you to your site/index.

And you can split your Site actionIndex() method to an authenticated or not part like:

public function actionIndex() {
    if(Yii::$app->user->isGuest) {
        return $this->redirect(Url::toRoute('site/login'));
    }
    else {
        ...
    }
}

Hope this helps.

查看更多
登录 后发表回答