Claims without roles?

别来无恙 提交于 2019-12-07 06:13:58

问题


I'm trying to understand ASP.NET Identity authentication and authorization mechanics. I understood what's a claim & what's a role. In almost every related blog post, or question on here it's advised to use claims and avoid roles. I'm confused at this point. How can I use claims without roles? (I normally assign roles to users after they are registered. )

Any help is appreciated.

Thank you


回答1:


Roles are claims too, claims are just more general.

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

I can only speculate, as you don't show exact links, that it's not exactly "claims over roles".

It's rather "use the claims-based security model over the role-based security model". This one is easy to explain, since roles are claims too, using claims you have roles but you have possibly other claims, too.

Technically, if you create a ClaimsPrincipal and add Role claims, ASP.NET will correctly recognize roles wherever you'd expect it to - WebForms authorization, MVC authorization filters and other role-based stuff works as usual.

If you need some technical details, consult my blog entry where I show how you easily switch from old role-based Forms Authentication to the new claims-based authentication.

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

In particular, you just add role claims like this

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  

However, what claims give you is the ability to do authorization based on arbitrary claims like "user is older than 18 years" or "user comes from France, Germany or Spain". Such arbitrary statements do not necessarily map to "roles" but are perfect claims.

You do this authorization with a custom claims authorization manager, examples here

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




回答2:


Claims and Roles can each be used separately. Roles on one hand control access based on what group they belong to whereas Claims control access based on various statements the user makes about themselves

The following two links provide an overview of Role and Claim based security and an example on how to use Claims within an attribute that can then be attached to a controller action and provide authorization similar to AuthorizeAttribute:

What is the claims in ASP .NET Identity

ASP.NET Claims Authorization with ASP.NET Identity



来源:https://stackoverflow.com/questions/29593214/claims-without-roles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!