Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

php - Yii2 require all Controller and Action to login

In my sitecontroller I write like this

    'access' => [
        'class' => AccessControl::className(),
        'rules' => [
            [
                'actions' => ['login', 'error'],
                'allow' => true,
            ],
            [
                'actions' => ['logout', 'index' ,'call-back'], // add all actions to take guest to login page
                'allow' => true,
                'roles' => ['@'],
            ],
        ],
    ],

so If I go to index or call-back action,I'll redirected to login page. but I have to do it for all action to each controller. Could you tell me the best way to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Place this rule in the beginning of the rules section:

[
    'allow' => true,
    'roles' => ['@'],
],

Omitting the actions means all actions.

So your AccessControl config will be like this:

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],

                // ...
            ],
        ],
    ];
}

Keep in mind that rules are applied in order they are declared.

To do it globally without inheritance, add the as beforeRequest array below (not inside!) the components declaration in your application config:

'components' => [ ... ],
'as beforeRequest' => [
    'class' => 'yiifiltersAccessControl',
    'rules' => [
        [
            'allow' => true,
            'actions' => ['login'],
        ],
        [
            'allow' => true,
            'roles' => ['@'],
        ],
    ],
    'denyCallback' => function () {
        return Yii::$app->response->redirect(['site/login']);
    },
],

This code will run before each request and block all actions except login for guests.

Make sure that there is no login action in other controllers than SiteController. If there are (and for example they are for different purposes), block them explicitly in according controllers. But it's pretty rare case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...