Tip You can use the browser F12 tools to see the cookies that are used to identify authenticated requests.
提示:可以用浏览器的F12工具,看到用来标识已认证请求的Cookie。
14.3 以角色授权用户
In the previous section, I applied the Authorize attribute in its most basic form, which allows any authenticated user to execute the action method. In this section, I will show you how to refine authorization to give finer-grained control over which users can perform which actions. Table 14-6 puts authorization in context.
上一小节以最基本的形式运用了Authorize注解属性,这允许任何已认证用户执行动作方法。在本小节中,将展示如何精炼授权,以便在用户能够执行的动作上有更细粒度的控制。表14-6描述了授权的情形。
表16-4. 授权情形
Question
问题
Answer
答案
What is it?
这是什么
Authorization is the process of granting access to controllers and action methods to certain users, generally based on role membership.
授权是将控制器和动作的准许访问限制到特定用户,通常是基于角色的成员
Why should I care?
为何要关注它
Without roles, you can differentiate only between users who are authenticated and those who are not. Most applications will have different types of users, such as customers and administrators.
没有角色,你只能在已认证用户和未认证用户之间加以区分。大多数应用程序均有不同类型的用户,例如客户和管理员等
How is it used by the MVC framework?
在MVC框架中如何使用
Roles are used to enforce authorization through the Authorize attribute, which is applied to controllers and action methods.
角色通过Authorize注解属性可用于强制授权,Authorize可用于控制器和动作方法
Tip In Chapter 15, I show you a different approach to authorization using claims, which are an advanced ASP.NET Identity feature.
提示:第15章将使用Claims(声明)来演示不同的授权办法,Claims是一种高级的ASP.NET Identity特性。
14.3.1 添加角色支持
ASP.NET Identity provides a strongly typed base class for accessing and managing roles called RoleManager<T> , where T is the implementation of the IRole interface supported by the storage mechanism used to represent roles. The Entity Framework uses a class called IdentityRole to implement the IRole interface, which defines the properties shown in Table 14-7.
ASP.NET Identity为访问和管理角色提供了一个强类型的基类,叫做RoleManager<T> ,其中T是IRole接口的实现,该实现得到了用来表示角色的存储机制的支持。Entity Framework实现了IRole接口,使用的是一个名称为IdentityRole的类,它定义了如表14-7所示的属性。
表14-7. IdentityRole类所定义的属性
Name
名称
Description
描述
Id
Defines the unique identifier for the role
定义角色的唯一标识符
Name
Defines the name of the role
定义角色名称
Users
Returns a collection of IdentityUserRole objects that represents the members of the role
返回一个代表角色成员的IdentityUserRole对象集合
I don’t want to leak references to the IdentityRole class throughout my application because it ties me to the Entity Framework for storing role data, so I start by creating an application-specific role class that is derived from IdentityRole. I added a class file called AppRole.cs to the Models folder and used it to define the class shown in Listing 14-6.
我不希望在整个应用程序中都暴露对IdentityRole类的引用,因为它为了存储角色数据,将我绑定到了Entity Framework。为此,我首先创建了一个应用程序专用的角色类,它派生于IdentityRole。我在Models文件夹中添加了一个类文件,名称为AppRole.cs,并用它定义了这个类,如清单14-6所示。