所有角色的 IP 访问规则
access rules by IP for all roles
在 Yii2 上,我试图将 create
操作限制为 只允许批准的 IP 无论用户是否登录。
这是我的代码
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'view', 'create'],
'rules' => [
[
'actions' => ['index','view'],
'allow' => true,
'roles' => ['@'],
],
[
'actions' => ['create'],
'allow' => true,
'ips' => Yii::$app->params['adminIPs'],
'roles' => ['?','@'],
],
],
],
如果用户已登录,并且不是允许的 ip。它显示 forbidden permission
页面,但如果用户 NOT
登录,它会重定向到登录页面。
如何让它在两种情况下都显示 403 forbidden 页面?
如果您想通过 IP 限制访问并且不关心用户是否登录,您可以省略角色。
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'view', 'create'],
'rules' => [
//....
[
'actions' => ['create'],
'allow' => true,
'ips' => Yii::$app->params['adminIPs'],
],
],
],
默认情况下,当规则拒绝访问 AccessControl::denyAccess()
method is called. If the user is guest (not logged in) they are redirected to login page by this method. If you want to return 403 Forbidden page instead you have to override this behavior by using AccessRule::$denyCallback
属性。
此外,您需要为拒绝访问的规则设置 denyCallback
属性,而不是允许访问的规则。
例如:
'access' => [
'class' => AccessControl::class,
'only' => ['index', 'view', 'create'],
'rules' => [
// ...
[
'actions' => ['create'],
'allow' => true,
'ips' => Yii::$app->params['adminIPs'],
],
[
'actions' => ['create'],
'allow' => false,
'denyCallback' => function() {
throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
}
]
],
],
因为该规则匹配所有内容,所以您需要确保它是 create
操作的最后一条规则,一旦这条规则匹配,下一条规则将不会达到。
在 Yii2 上,我试图将 create
操作限制为 只允许批准的 IP 无论用户是否登录。
这是我的代码
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'view', 'create'],
'rules' => [
[
'actions' => ['index','view'],
'allow' => true,
'roles' => ['@'],
],
[
'actions' => ['create'],
'allow' => true,
'ips' => Yii::$app->params['adminIPs'],
'roles' => ['?','@'],
],
],
],
如果用户已登录,并且不是允许的 ip。它显示 forbidden permission
页面,但如果用户 NOT
登录,它会重定向到登录页面。
如何让它在两种情况下都显示 403 forbidden 页面?
如果您想通过 IP 限制访问并且不关心用户是否登录,您可以省略角色。
'access' => [
'class' => AccessControl::className(),
'only' => ['index', 'view', 'create'],
'rules' => [
//....
[
'actions' => ['create'],
'allow' => true,
'ips' => Yii::$app->params['adminIPs'],
],
],
],
默认情况下,当规则拒绝访问 AccessControl::denyAccess()
method is called. If the user is guest (not logged in) they are redirected to login page by this method. If you want to return 403 Forbidden page instead you have to override this behavior by using AccessRule::$denyCallback
属性。
此外,您需要为拒绝访问的规则设置 denyCallback
属性,而不是允许访问的规则。
例如:
'access' => [
'class' => AccessControl::class,
'only' => ['index', 'view', 'create'],
'rules' => [
// ...
[
'actions' => ['create'],
'allow' => true,
'ips' => Yii::$app->params['adminIPs'],
],
[
'actions' => ['create'],
'allow' => false,
'denyCallback' => function() {
throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.'));
}
]
],
],
因为该规则匹配所有内容,所以您需要确保它是 create
操作的最后一条规则,一旦这条规则匹配,下一条规则将不会达到。