是否可以将RBAC yii\rbac\Rule应用于未经身份验证的用户(Yii::$app->user->isGuest == true
)?如果是这样,怎么样?
我所使用的规则也用于经过身份验证的用户,将所有逻辑保存在一个位置会很好并且干,这样:
class UserAccesslevelRule extends Rule {
public $name = 'userAccesslevel';
public function execute($userID, $item, $params) {
if (Yii::$app->user->isGuest && $someotherlogic == true) {
return true;
} else {
if ($somelogic == true) {
return true;
}
}
return false;
}
}
答案 0 :(得分:0)
您可以使用ACF(访问控制过滤器)在控制器中为您分配允许访客的操作
来自Yii2指南的
use yii\web\Controller; use yii\filters\AccessControl; class SiteController extends Controller { public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'only' => ['login', 'logout', 'signup'], 'rules' => [ [ 'allow' => true, 'actions' => ['login', 'signup'], 'roles' => ['?'], // <----- guest ], [ 'allow' => true, 'actions' => ['logout'], 'roles' => ['@'], ], ], ], ]; } // ... }
http://www.yiiframework.com/doc-2.0/guide-security-authorization.html
使用RBAC,您还可以定义新规则,查看新规则http://www.yiiframework.com/doc-2.0/guide-security-authorization.html#using-rules,但似乎您要重新定义guest的行为.. isGuest属性和getIsGuest()公共方法被定义{{3可能是这样你应该扩展这个类并重新定义isGuest函数..
答案 1 :(得分:0)
在Controller中,你可以这样做
use yii\filters\AccessControl;
class controllerName extends Controller {
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['index','Other_action_names'],
'rules' => [
[
'allow' => true,
'actions' => ['index','Other_action_names'],
'roles' => (Yii::$app->user->isGuest) ? ["@"] : [], // Your roles
],
],
],
];
}
public function actionIndex() {
$searchModel = new SearchModel();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
}
希望这对你有用。