问题
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