Yii2需要所有Controller和Action才能登录 [英] 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?
推荐答案
将此规则放在rules
部分的开头:
Place this rule in the beginning of the rules
section:
[
'allow' => true,
'roles' => ['@'],
],
省略actions
表示所有操作.
因此您的AccessControl
配置将如下所示:
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.
要在不继承的情况下全局进行操作,请在应用程序配置中的components
声明下面(不在内部!)添加as beforeRequest
数组:
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' => 'yii\filters\AccessControl',
'rules' => [
[
'allow' => true,
'actions' => ['login'],
],
[
'allow' => true,
'roles' => ['@'],
],
],
'denyCallback' => function () {
return Yii::$app->response->redirect(['site/login']);
},
],
此代码将在每个请求之前运行,并阻止来宾执行除login
之外的所有操作.
This code will run before each request and block all actions except login
for guests.
确保除SiteController
以外的其他控制器中没有任何login
操作.如果存在(例如,它们出于不同的目的),请在相应的控制器中明确阻止它们.但这是非常罕见的情况.
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.
这篇关于Yii2需要所有Controller和Action才能登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!