没有角色的声明?

Claims without roles?

我正在尝试了解 ASP.NET 身份验证和授权机制。我明白什么是主张,什么是角色。在几乎所有相关博客 post 或此处的问题中,建议使用声明并避免使用角色。我现在很困惑。如何在没有角色的情况下使用声明? (我一般都是在用户注册后给他们分配角色。)

感谢任何帮助。

谢谢

声明和角色可以分别使用。一方面,角色根据他们属于哪个组来控制访问,而声明则根据用户对自己所做的各种陈述来控制访问

以下两个链接提供了基于角色和声明的安全性的概述,以及有关如何在属性中使用声明的示例,该属性随后可以附加到控制器操作并提供类似于 AuthorizeAttribute 的授权:

What is the claims in ASP .NET Identity

ASP.NET Claims Authorization with ASP.NET Identity

角色也是声明,声明只是更笼统。

In almost every related blog post, or question on here it's advised to use claims and avoid roles.

我只能推测,因为您没有显示确切的链接,所以它不完全是 "claims over roles"。

而是"use the claims-based security model over the role-based security model"。这个很容易解释,因为角色也是声明,使用声明你有角色但你也可能有其他声明。

从技术上讲,如果您创建 ClaimsPrincipal 并添加 Role 声明,ASP.NET 将在您期望的任何位置正确识别角色 - WebForms 授权、MVC 授权过滤器和其他基于角色的东西照常工作。

如果您需要一些技术细节,请查阅我的博客条目,我在其中展示了如何轻松地从旧的基于角色的表单身份验证切换到新的基于声明的身份验证。

http://www.wiktorzychla.com/2014/11/forms-authentication-revisited-for-net.html

特别是,您只需像这样添加角色声明

var identity = new ClaimsIdentity( "custom" );
identity.AddClaim( new Claim( ClaimTypes.Name, txtLogin.Text ) );
identity.AddClaim( new Claim( ClaimTypes.Role, "admin" ) );

var principal = new ClaimsPrincipal( identity );

// write the principal to cookie  

但是,声明赋予您的是基于任意 声明(如"user is older than 18 years" 或"user comes from France, Germany or Spain" 进行授权的能力。此类任意陈述不一定映射到 "roles",而是完美的声明。

您使用自定义索赔授权管理器进行此授权,此处示例

https://msdn.microsoft.com/en-us/library/system.security.claims.claimsauthorizationmanager(v=vs.110).aspx