YII2 的授权(Authorization)

来源:互联网 发布:淘一兔淘宝号查询 编辑:程序博客网 时间:2024/06/06 00:46

说明:翻译本不是我应该做的,因为我的英语水平实在太差。但因为对YII的兴趣,所以也做一点,同时也能显示出我的胆量还是有的。。。希望不误导您。因为这里MD语法的内容显示不全,您可以去这里看看。


Authorization 授权

Note: This section is under development.

注意:这一节还在完善中。

Authorization is the process of verifying that a user has enough permission to do something. Yii provides two authorization methods: Access Control Filter (ACF) and Role-Based Access Control (RBAC).

授权是用来检验一个用户有足够权限来做些事情的举措。Yii提供两种授权方法:访问控制过滤(ACF)和基于角色的访问控制(RBAC)。

Access Control Filter 访问控制过滤

Access Control Filter (ACF) is a simple authorization method that is best used by applications that only need some simple access control. As its name indicates, ACF is an action filter that can be attached to a controller or a module as a behavior. ACF will check a set of [[yii\filters\AccessControl::rules|access rules]] to make sure the current user can access the requested action.

访问控制过滤(ACF)是一个简单的授权方法,非常适合于在只需要一些简单访问控制的程序中使用。正如名字所标示的,访问控制过滤(ACF)是一个动作过滤,它可以作为一个扩展附加到一个控制器或是一个模块。访问控制过滤(ACF)将会检查一套[[yii\filters\AccessControl::rules|accessrules]] 来确定当前用户能够访问请求的动作。

The code below shows how to use ACF which is implemented as [[yii\filters\AccessControl]]:

下面的代码显示如何使用访问控制过滤(ACF),它已经被实现为[[yii\filters\AccessControl]]:

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' => ['?'],                    ],                    [                        'allow' => true,                        'actions' => ['logout'],                        'roles' => ['@'],                    ],                ],            ],        ];    }    // ...}

In the code above ACF is attached to the site controller as a behavior. This is the typical way of using an action filter. Theonly option specifies that the ACF should only be applied tologin,logout andsignup actions. The rules option specifies the [[yii\filters\AccessRule|access rules]], which reads as follows:

在上面的代码中,访问控制过滤(ACF)作为一个扩展附加到site控制器中。这是一个典型使用动作过滤的方式。only选项指定访问控制过滤(ACF)将只能用于登录、登出和注册动作。rules选项指定[[yii\filters\AccessRule|accessrules]],它应作如下理解:

  • Allow all guest (not yet authenticated) users to access 'login' and 'signup' actions. Theroles option contains a question mark? which is a special token recognized as "guests".
  • 允许所有的访客(没有授权过的)、用户访问登录和注册动作。roles选项包含一个问号(?),它是一个标志,代表着“访客”。
  • Allow authenticated users to access 'logout' action. The @ character is another special token recognized as authenticated users.
  • 允许已授权的用户访问登出动作。字符@是另一个标志,代表着已授权用户。

When ACF performs authorization check, it will examine the rules one by one from top to bottom until it finds a match. Theallow value of the matching rule will then be used to judge if the user is authorized. If none of the rules matches, it means the user is NOT authorized and ACF will stop further action execution.

当访问控制过滤(ACF)进行授权检查时,它会从上到下地一个接着一个地测试那些规则直至找到一个相符的。相符的允许值将立即用于判断用户是否被授权。如果没有一个规则符合,这就意味着这个用户“没有”被授权,访问控制过滤(ACF)将阻止它进一步的动作请求。

By default, ACF does only of the followings when it determines a user is not authorized to access the current action:

默认情况下,当访问控制过滤(ACF)探测到一个用户没有被授权进入当前动作时,它只会作下面的工作:

  • If the user is a guest, it will call [[yii\web\User::loginRequired()]], which may redirect the browser to the login page.
  • 如果这个用户是个访客,ACF将会调用[[yii\web\User::loginRequired()]],将浏览器重定向到登录页面。
  • If the user is already authenticated, it will throw a [[yii\web\ForbiddenHttpException]].
  • 如果用户已有授权,ACF会抛出一个[[yii\web\ForbiddenHttpException]]。

You may customize this behavior by configuring the [[yii\filters\AccessControl::denyCallback]] property:

你可以通过定义配置[[yii\filters\AccessControl::denyCallback]]的属性来对这个扩展进行自定义:

[    'class' => AccessControl::className(),    'denyCallback' => function ($rule, $action) {        throw new \Exception('You are not allowed to access this page 您没有被允许访问这个页面!');    }]

[[yii\filters\AccessRule|Access rules]] support many options. Below is a summary of the supported options. [[yii\filters\AccessRule|Access rules]]支持许多选项。下面是它支持的选项的概览。

You may also extend [[yii\filters\AccessRule]] to create your own customized access rule classes.

你也可以扩展[[yii\filters\AccessRule]]来创建你自己定义的访问规则类。

  • [[yii\filters\AccessRule::allow|allow]]: specifies whether this is an "allow" or "deny" rule.
  • [[yii\filters\AccessRule]]:指定是一个“允许”规则还是一个“禁止”规则。

  • [[yii\filters\AccessRule::actions|actions]]: specifies which actions this rule matches. This should be an array of action IDs. The comparison is case-sensitive. If this option is empty or not set, it means the rule applies to all actions.

  • [[yii\filters\AccessRule]]:指定这个规则与哪些动作匹配。这应该是一个动作的ID的数组。比较是区分大小写的。如果这个选项是空的或是没有设置,这意味着这个规则适用于所有的动作。

  • [[yii\filters\AccessRule::controllers|controllers]]: specifies which controllers this rule matches. This should be an array of controller IDs. The comparison is case-sensitive. If this option is empty or not set, it means the rule applies to all controllers.

  • [[yii\filters\AccessRule::controllers|controllers]]:指定这个规则与哪些控制器匹配。这应该是一个控制器的ID的数组。比较是区分大小写的。如果这个选项是空的或是没有设置,这意味着这个规则适用于所有的控制器。

  • [[yii\filters\AccessRule::roles|roles]]: specifies which user roles that this rule matches. Two special roles are recognized, and they are checked via [[yii\web\User::isGuest]]:

  • [[yii\filters\AccessRule::roles|roles]]:指定这个规则与哪些用户角色匹配。两个特别的用户角色已经被确立,它们将通过[[yii\web\User::isGuest]]来检查。

    • ?: matches a guest user (not authenticated yet)
    • ?:匹配访客(还没有被授权)
    • @: matches an authenticated user
    • @:匹配一个已授权用户

Using other role names requires RBAC (to be described in the next section), and [[yii\web\User::can()]] will be called. If this option is empty or not set, it means this rule applies to all roles.

使用其他角色名称(需要基于角色的访问控制(RBAC),将在下一节说明)的已授权用户,将会调用[[yii\web\User::can()]]。如果这个选项是空的或是没有设置,这意味着这个规则适用于所有的角色。

  • [[yii\filters\AccessRule::ips|ips]]: specifies which [[yii\web\Request::userIP|client IP addresses]] this rule matches. An IP address can contain the wildcard* at the end so that it matches IP addresses with the same prefix. For example, '192.168.*' matches all IP addresses in the segment '192.168.'. If this option is empty or not set, it means this rule applies to all IP addresses.
  • [[yii\filters\AccessRule::ips|ips]]:指定这个规则匹配哪一个[[yii\web\Request::userIP|clientIP addresses]]。一个IP地址可以在末尾包含一个通配符,这样就可以匹配具有相同前缀的所有IP地址。比如,“192.168.”,匹配“192.168.”节中所有的IP地址。如果这个选项是空的或是没有设置,这意味着这个规则适用于所有的IP。
  • [[yii\filters\AccessRule::verbs|verbs]]: specifies which request method (e.g.GET,POST) this rule matches. The comparison is case-insensitive.
  • [[yii\filters\AccessRule::verbs|verbs]]:指定这个规则匹配哪种请求方法(比如GET,POST)。比较是区分大小写的。
  • [[yii\filters\AccessRule::matchCallback|matchCallback]]: specifies a PHP callable that should be called to determine if this rule should be applied.
  • [[yii\filters\AccessRule::matchCallback|matchCallback]]:指定一个PHP可调用,它将被调用来检查这个规则是否可以执行。
  • [[yii\filters\AccessRule::denyCallback|denyCallback]]: specifies a PHP callable that should be called when this rule will deny the access.
  • [[yii\filters\AccessRule::denyCallback|denyCallback]]:指定一个PHP可调用,在这个规则拒绝访问时它将被调用。

Below is an example showing how to make use of the matchCallback option, which allows you to write arbitrary access check logic:

下面是一个例子,显示如何使用matchCallback选项,它将能让你写出任意访问控制逻辑:

use yii\filters\AccessControl;class SiteController extends Controller{    public function behaviors()    {        return [            'access' => [                'class' => AccessControl::className(),                'only' => ['special-callback'],                'rules' => [                    [                        'actions' => ['special-callback'],                        'allow' => true,                        'matchCallback' => function ($rule, $action) {                            return date('d-m') === '31-10';                        }                    ],                ],            ],        ];    }    // Match callback called! This page can be accessed only each October 31st    // Match callback被调用!这个页面只能在每一个十月31日才能访问    public function actionSpecialCallback()    {        return $this->render('happy-halloween');    }}

Role based access control (RBAC) 基于角色的访问控制(RBAC)

Role-Based Access Control (RBAC) provides a simple yet powerful centralized access control. Please refer to theWiki article for details about comparing RBAC with other more traditional access control schemes.

基于角色的访问控制(RBAC)提供一个简单但强大的集中式访问控制。请参考维基文章来获取更多关于比较RBAC和其他传统访问控制框架的细节。

Yii implements a General Hierarchical RBAC, following the NIST RBAC model. It provides the RBAC functionality through the [[yii\rbac\ManagerInterface|authManager]] application component.

Yii提供一个通用层级RBAC,参照的是 NIST RBAC model。它通过[[yii\rbac\ManagerInterface|authManager]]应用程序组件提供RBAC功能。

Using RBAC involves two parts of work. The first part is to build up the RBAC authorization data, and the second part is to use the authorization data to perform access check in places where it is needed.

使用RBAC包含两个部分的工作。第一部分是建立一个RBAC授权数据,第二部分是在需要的地方使用这个授权数据来执行访问检查。

To facilitate our description next, we will first introduce some basic RBAC concepts.

为了便于说明,我们先介绍一些RBAC基本概念。

Basic Concepts 基本概念

A role represents a collection of permissions (e.g. creating posts, updating posts). A role may be assigned to one or multiple users. To check if a user has a specified permission, we may check if the user is assigned with a role that contains that permission.

一个角色代表一个允许的集合(例如,写新文章,修改文章)。一个角色会被分配给一个或多个用户。要检查一个用户是不是具有特定的许可,我们可以检查这个用户是否分配给了包含这个许可的角色。

Associated with each role or permission, there may be a rule. A rule represents a piece of code that will be executed during access check to determine if the corresponding role or permission applies to the current user.

与一个角色和一个许可联系,可能需要一个规则。一个规则代表着一些代码,它们将在访问检查时执行,用以检查相应的角色或是许可适用于当前用户。

For example, the "update post" permission may have a rule that checks if the current user is the post creator. During access checking, if the user is NOT the post creator, he/she will be considered not having the "update post" permission.

比如,“更新文章”的许可可能就包含一个规则,用来检查当前用户是不是文章的作者。在访问检查时,如果这个用户不是文章的作者,他或者她将被认为是没有“更新文章”的许可。

Both roles and permissions can be organized in a hierarchy. In particular, a role may consist of other roles or permissions; and a permission may consist of other permissions. Yii implements apartial order hierarchy which includes the more special tree hierarchy. While a role can contain a permission, it is not true vice versa.

规则和许可可以被组织到一个层次中。特别是,一个角色可以包含其他角色或是许可,而且一个许可可以包含其他许可。Yii执行一个“偏向”次序层次,它包含非常特别的树形层次。一个角色可以包含一个许可,但这不能反过来。

Configuring RBAC Manager 配置基于角色的访问控制(RBAC)管理器

Before we set off to define authorization data and perform access checking, we need to configure the [[yii\base\Application::authManager|authManager]] application component. Yii provides two types of authorization managers:

在我开始定义授权数据和进行访问检查之前,我们需要去配置[[yii\base\Application::authManager|authManager]]应用程序组件。Yii提供两种授权管理器:

[[yii\rbac\PhpManager]] and [[yii\rbac\DbManager]]. The former uses a PHP script file to store authorization data, while the latter stores authorization data in database. You may consider using the former if your application does not require very dynamic role and permission management.

[[yii\rbac\PhpManager]]和[[yii\rbac\DbManager]]。以前的人使用PHP脚本文件来储存授权数据,但后来的人用数据库来储存授权数据。如果你的应用程序并不需要非常动态的角色和许可管理,你可以考虑使用前者。

The following code shows how to configure authManager in the application configuration:

下面的代码显示如何在应用程序配置中去配置授权管理器。

return [    // ...    'components' => [        'authManager' => [            'class' => 'yii\rbac\PhpManager',        ],        // ...    ],];

The authManager can now be accessed via \Yii::$app->authManager.

授权管理器现在可以通过\Yii::$app->authManager来访问。

Building Authorization Data 创建授权数据

Building authorization data is all about the following tasks:

创建授权数据包含列任务:

  • defining roles and permissions;
  • 定义角色和许可;
  • establishing relations among roles and permissions;
  • 在角色和许可间建立关系;
  • defining rules;
  • 定义规则;
  • associating rules with roles and permissions;
  • 把规则跟角色和许可关联起来;
  • assigning roles to users.
  • 分配角色给用户。

Depending on authorization flexibility requirements the tasks above could be done in different ways.

基于授权灵活性的需要,上述任务可以用不同方式来完成。

If your persmissions hierarchy doesn't change at all and you have a fixed number of users you can create a console command that will initialize authorization data once via APIs offered byauthManager:

如果你的许可层次不再改变,而且你拥有的是固定数量的用户,你可以创建一个控制台命令,它将使用授权管理器提供的编程接口,一次性地为您初始化授权数据。(译注:原文这一句中有个词错了,permissions写成了persmissions)

<?phpnamespace app\commands;use yii\console\Controller;class RbacController extends Controller{    public function actionInit()    {        $auth = Yii::$app->authManager;        // add "createPost" permission        // 添加”创建文章”许可        $createPost = $auth->createPermission('createPost');        $createPost->description = 'Create a post';        $auth->add($createPost);        // add "updatePost" permission        // 添加”更新文章”许可        $updatePost = $auth->createPermission('updatePost');        $updatePost->description = 'Update post';        $auth->add($updatePost);        // add "author" role and give this role the "createPost" permission        // 添加“作者”角色,接着赋予这个角色“创建文章”的许可        $author = $auth->createRole('author');        $auth->add($author);        $auth->addChild($author, $createPost);        $auth->addChild($author, $reader);        // add "admin" role and give this role the "updatePost" permission        // 添加“管理员”角色,接着赋予这个角色“更新文章”的许可        // as well as the permissions of the "author" role        // 与“作者角色的一样        $admin = $auth->createRole('admin');        $auth->add($admin);        $auth->addChild($admin, $updatePost);        $auth->addChild($admin, $author);        // Assign roles to users. 1 and 2 are IDs returned by IdentityInterface::getId()        // 分配角色给用户。1和2是用户ID,用IdentityInterface::getId()获取到的        // usually implemented in your User model.        // 经常出现在您的User模块中。        $auth->assign($author, 2);        $auth->assign($admin, 1);    }}

After executing the command we'll get the following hierarchy:

在运行这个命令之后我们得到了下列的层次:

Simple RBAC hierarchy 简单的RBAC层次

Author can create post, admin can update post and do everything author can.

作者可以创建文章,管理员可以更新文章,同时可以做所有作者能做的事。

If your application allows user signup you need to assign roles to these new users once. For example, in order for all signed up users to become authors you in advanced application template you need to modifyfrontend\models\SignupForm::signup() as follows:

如果你的应用程序允许用户注册,你需要分配一次角色给那些新用户。举个例子,要想使所有注册的用户成为作者,在高级应用程序模板(advancedapplication template)中,你必须像下面这样去修改frontend\models\SignupForm::signup()。(译注,这一句中好像在authors后面多了一个you,我语法不好,瞎猜的)

public function signup(){    if ($this->validate()) {        $user = new User();        $user->username = $this->username;        $user->email = $this->email;        $user->setPassword($this->password);        $user->generateAuthKey();        $user->save(false);        // the following three lines were added:        // 加上下面这三行:        $auth = Yii::$app->authManager;        $authorRole = $auth->getRole('author');        $auth->assign($authorRole, $user->getId());        return $user;    }    return null;}

For applications that require complex access control with dynamically updated authorization data, special user interfaces (i.e. admin panel) may need to be developed using APIs offered byauthManager.

因为一些应用程序需要带动态更新授权数据的复杂的访问控制,可能需要用授权管理器提供的编程接口来开发特定的用户接口界面(比如,控制板)

Tip: By default, [[yii\rbac\PhpManager]] stores RBAC data in the file @app/data/rbac.php. Sometimes when you want to make some minor changes to the RBAC data, you may directly edit this file.

小窍门:默认情况下,[[yii\rbac\PhpManager]]保存RBAC数据在文件 @app/data/rbac.php。有时如果你想要对RBAC数据做一点细小的修改,你可以直接修改这个文件。

Using Rules 使用规则

As aforementioned, rules add additional constraint to roles and permissions. A rule is a class extending from [[yii\rbac\Rule]]. It must implement the [[yii\rbac\Rule::execute()|execute()]] method. In the hierarchy we've created previously author cannot edit his own post. Let's fix it. First we need a rule to verify that the user is the post author:

正如前面已经提到的,规则给角色和许可添加额外的限制。一个规则是一个类,从[[yii\rbac\Rule]]扩展而来。它必须执行[[yii\rbac\Rule::execute()|execute()]]方法。在我们先前创建的层次中,作者不能编辑他自己的文章。让我们来改进它。首先我们需要一个规则来判定这个用户是文章的作者。(译注:这里的use应该是user)

namespace app\rbac;use yii\rbac\Rule;/** * Checks if authorID matches user passed via params * 检查authorID是否与已经通过参数(译注:不明白!)的用户匹配 */class AuthorRule extends Rule{    public $name = 'isAuthor';    /**     * @param string|integer $user the user ID.     * @param Item $item the role or permission that this rule is associated with     * @param array $params parameters passed to ManagerInterface::checkAccess().     * @return boolean a value indicating whether the rule permits the role or permission it is associated with.     */    public function execute($user, $item, $params)    {        return isset($params['post']) ? $params['post']->createdBy == $user : false;    }}

The rule above checks if the post is created by $user. We'll create a special permissionupdateOwnPost in the command we've used previously:

上面这个规则检查这篇文章是否是这个$user创建的。我们可以用前面已经用过的命令来创建一个特定的许可updateOwnPost:

// add the rule// 添加规则$rule = new \app\rbac\AuthorRule;$auth->add($rule);// add the "updateOwnPost" permission and associate the rule with it.// 添加“updateOwnPost”许可,再把它联系到角色上。$updateOwnPost = $this->auth->createPermission('updateOwnPost');$updateOwnPost->description = 'Update own post';$updateOwnPost->ruleName = $rule->name;$auth->add($updateOwnPost);// "updateOwnPost" will be used from "updatePost"// “updateOwnPost”将从“updatePost”开始使用$auth->addChild($updateOwnPost, $updatePost);// allow "author" to update their own posts// 允许“author"修改他们自己的文章$auth->addChild($author, $updateOwnPost);

Now we've got the following hierarchy:

现在我们有了如下的层次:

RBAC hierarchy with a rule 带一个规则的RBAC层次

Access Check 访问检查

With the authorization data ready, access check is as simple as a call to the [[yii\rbac\ManagerInterface::checkAccess()]] method. Because most access check is about the current user, for convenience Yii provides a shortcut method [[yii\web\User::can()]], which can be used like the following:

在授权数据已经具备的情况下,访问检查就如同调用一个[[yii\rbac\ManagerInterface::checkAccess()]]方法那样简单。因为大多数访问检查是与当前用户有关的,为了更方便点,Yii提供了一个快捷方法[[yii\web\User::can()]],它能像下面这样使用:

if (\Yii::$app->user->can('createPost')) {    // create post    // 创建文章}

If the current user is Jane with ID=1 we're starting at createPost and trying to get toJane:

如果当前用户是Jane并且她的ID=1,我们是从创建文章开始并且试着去抓住Jane。(译注:get to Jane不知道是什么意思,先就这样吧)

Access check 访问检查

In order to check if user can update post we need to pass an extra parameter that is required by theAuthorRule described before:

为了检查用户能够修改文章,我们需要传递一个额外的参数,这是之前定义的AuthorRule所需要的:

if (\Yii::$app->user->can('updatePost', ['post' => $post])) {    // update post    // 修改文章}

Here's what happens if current user is John: 如果当前用户是John,将会出现下面的情形:

Access check 访问检查

We're starting with the updatePost and going through updateOwnPost. In order to pass itAuthorRule should returntrue from itsexecute method. The method receives its$params fromcan method call so the value is['post' => $post]. If everything is OK we're getting toauthor that is assigned to John.

我们从修改文章开始,然后完成修改自己的文章。为了通过这,AuthorRule将会从它自己的运行方法中返回一个真。这个方法接收到它的$params从can方法调用中,,这个值是['post' => $post]。如果所有的事项都正确,我们将得到已经分配给John的author角色。

In case of Jane it is a bit simpler since she's an admin:

在Jane那里,事情就很简单了,因为她是一个管理员。

Access check 访问检查

Using Default Roles 使用默认角色

A default role is a role that is implicitly assigned to all users. The call to [[yii\rbac\ManagerInterface::assign()]] is not needed, and the authorization data does not contain its assignment information.

默认角色指的是一个无疑问地分配给了所有用户的角色。不需要调用[[yii\rbac\ManagerInterface::assign()]],而且授权数据中也不包含它的分配信息。

A default role is usually associated with a rule which determines if the role applies to the user being checked.

默认角色通常关联一个规则,它用于检测这个角色是否适用于将要检查的用户。

Default roles are often used in applications which already have some sort of role assignment. For example, an application may have a "group" column in its user table to represent which privilege group each user belongs to. If each privilege group can be mapped to a RBAC role, you can use the default role feature to automatically assign each user to a RBAC role. Let's use an example to show how this can be done.

默认角色经常用于一些应用程序,这些程序中已经包含一些角色分配。举个例子,一个应用程序可能在它的用户表中包含一个“group(分组)”字段,用以代表哪些特权分组是每一个用户都拥有的。如果每一个特权分组能够都能指向一个RBAC角色,你就能用默认角色功能来自动分配每一个用户到一个RABC角色。(译注:不好译)我们用一个例子来说明这是怎样实现的。

Assume in the user table, you have a group column which uses 1 to represent the administrator group and 2 the author group. You plan to have two RBAC rolesadmin andauthor to represent the permissions for these two groups, respectively. You can create set up the RBAC data as follows,

假定在一个用户表中,你有一个分组字段,它用1代表管理员组,用2代表作者组。你打算拥有两个RBAC角色,admin和author,分别代表这两个分组的许可。你可以用下面的办法来创建一个设置。

namespace app\rbac;use Yii;use yii\rbac\Rule;/** * Checks if authorID matches user passed via params */class UserGroupRule extends Rule{    public $name = 'userGroup';    public function execute($user, $item, $params)    {        if (!Yii::$app->user->isGuest) {            $group = Yii::$app->user->identity->group;            if ($item->name === 'admin') {                return $group == 1;            } elseif ($item->name === 'author') {                return $group == 1 || $group == 2;            }        }        return false;    }}$rule = new \app\rbac\UserGroupRule;$auth->add($rule);$author = $auth->createRole('author');$author->ruleName = $rule->name;$auth->add($author);// ... add permissions as children of $author ...// ... 添加许可给$author的子内容(译注:?)...$admin = $auth->createRole('admin');$admin->ruleName = $rule->name;$auth->add($admin);$auth->addChild($admin, $author);// ... add permissions as children of $admin ...// ... 添加许可给$admin的子内容 ...

Note that in the above, because "author" is added as a child of "admin", when you implement theexecute() method of the rule class, you need to respect this hierarchy as well. That is why when the role name is "author", theexecute() method will return true if the user group is either 1 or 2 (meaning the user is in either "admin" group or "author" group).

注意,在上面的例子中,因为“author”(作者)已经添加为“admin”的子内容,如果你执行那个规则类中的execute()方法,你也应当尊重这个层次。这就是为什么当角色名字是“author”时,只要用户分组是1或是2,那个execute()方法会返回一个真(意味着用户们不是在“admin(管理员)”分组就是在“author作者”分组)

Next, configure authManager by listing the two roles in [[yii\rbac\BaseManager::$defaultRoles]]:

下一步,配置授权管理器在[[yii\rbac\BaseManager::$defaultRoles]]中来监听这两个角色:

return [    // ...    'components' => [        'authManager' => [            'class' => 'yii\rbac\PhpManager',            'defaultRoles' => ['admin', 'author'],        ],        // ...    ],];

Now if you perform an access check, both of the admin and author roles will be checked by evaluating the rules associated with them. If the rule returns true, it means the role applies to the current user. Based on the above rule implementation, this means if the group value of a user is 1, the admin role would apply to the user; and if the group value is 2, theauthor role would apply.

现在,如果你执行一个访问检查,无论是admin角色还是author角色,都会被评价规则已经关联到它们这个方式来检查。(译注:真别扭,可能译错了)如果规则返回真,这意味着这个角色适用于当前用户。基于上述规则原则,这说明,如果一个用户的分组是1,那么管理员角色就适用于他;如果分组是2,作者角色将适用于他。


0 0
原创粉丝点击