码迷,mamicode.com
首页 > 其他好文 > 详细

YII2 的授权(Authorization)

时间:2017-05-28 20:14:48      阅读:573      评论:0      收藏:0      [点我收藏+]

标签:figure   没有   href   tab   intro   style   let   conf   拒绝   

说明:翻译本不是我应该做的,由于我的英语水平实在太差。但由于对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)

<?php
namespace 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:

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

技术分享

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:

如今我们有了例如以下的层次:

技术分享

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不知道是什么意思,先就这样吧)

技术分享

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,将会出现以下的情形:

技术分享

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那里,事情就非常easy了,由于她是一个管理员。

技术分享

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,作者角色将适用于他。

??

YII2 的授权(Authorization)

标签:figure   没有   href   tab   intro   style   let   conf   拒绝   

原文地址:http://www.cnblogs.com/lxjshuju/p/6916420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!