In Yii (both Yii 1 and Yii 2), access control is typically managed using the Access Control Filter (ACF) or through RBAC (Role-Based Access Control).
Yii Access Control Basics
-
Access Control Filter (ACF):
- Usually defined via behaviors() in controllers (Yii2) or filters() in Yii1.
- Allows restricting actions to certain users, roles, or other conditions.
- Typical rules specify who can perform what actions, e.g.:
public function behaviors()
{
return [
'access' => [
'class' => \yii\filters\AccessControl::class,
'only' => ['create', 'update'],
'rules' => [
[
'allow' => true,
'roles' => ['@'], // authenticated users
],
[
'allow' => true,
'roles' => ['admin'], // users with 'admin' role
],
],
],
];
}
-
Role-Based Access Control (RBAC):
- More granular, defines roles and permissions in the auth manager.
- You assign roles to users, and then protect actions by checking roles/permissions.
- Roles are strings you define (like 'admin', 'editor', etc.). The special
@ means "any authenticated user" (any logged in user).
Understanding the @ and roles in access rules
@ — special role/placeholder meaning "any authenticated user".
? — means guest users (not logged in).
- Other strings (like 'admin', 'editor') correspond to roles defined in your RBAC.
How does Yii evaluate rules if you specify both @ and roles?
Let's consider the example:
'rules' => [
[
'allow' => true,
'roles' => ['@'], // any authenticated user
],
[
'allow' => true,
'roles' => ['admin'], // admin role
],
],
- Yii processes rules in order.
- If the first rule matches (
roles => @) and allows access, then the request is allowed immediately.
- The second rule won't be checked because the first rule already allowed access.
So what happens if you "use @ for user but then add a role"?
- If you list
['@'] first in the rules, any authenticated user will be allowed access regardless of role.
- Because the rules are processed sequentially, the more general
@ rule will effectively trump any further role-checking rules.
If you want roles to have precedence over the general authenticated user rule, you should order your rules with more specific roles first:
'rules' => [
[
'allow' => true,
'roles' => ['admin'], // grant access only to admins first
],
[
'allow' => true,
'roles' => ['@'], // then allow all authenticated users (less privileged)
],
],
The above will allow admin users first (should they reach those actions), and then allow any authenticated user for other applicable actions.
Summary:
@ means any authenticated user.
- Specific role names (like 'admin') mean users assigned to that role.
- Rules are evaluated in order; the first matched allow or deny is applied.
- If the
@ rule is before the role rules, it will override role checks (because any logged-in user matches @).
- To have role rules take effect, place them before the
@ rule in the rules array.
Let me know if you'd like an example or details on RBAC setup!