I start by authorizing ASP.NET Identity Claim, and I would like to clarify how to continue working with them if I need the concept of "role" in my application.
Note: I'm really new to this, so all the concepts fly in my head, please be kind and further clarifications / corrections regarding any concept will be highly appreciated.
1. Suppose I need the concept of "roles" for the roles of administrator and user, so my first one, although I had to add claims to ApplicationUser as follows:
user.Claims.Add(new IdentityUserClaim<string> { ClaimType = "Role", ClaimValue = "Admin" });
* Where the "user" is ApplicationUser .
But then I read that this has already been done by the framework, as it has some predefined claim types, so the code above could be:
user.Claims.Add(new IdentityUserClaim<string> { ClaimType = ClaimTypes.Role, ClaimValue = "Admin" });
Is this approach right? Or should I use the "old" concept of the role and add the role to the user, for example:
await _roleManager.CreateAsync(new IdentityRole("Admin")); await _userManager.AddToRoleAsync(user, "Admin");
2. Now suppose I have roles defined as claims, how can I check their autofocus? I mean, does this work?
[Authorize(Roles = "Admin")]
Or should I include a policy expression to validate a role request?
options.AddPolicy("IsAdmin", policy => { policy.RequireClaim(ClaimTypes.Role, "Admin"); }); ... [Authorize(Policy = "IsAdmin")] <controller here>
3.- And now, what is the correct way to store my user requirements? I mean, the ASP.NET ClaimTypes class is just a set of const string values, and all the complaints code examples store them in similar classes, for example:
public static class ClaimData { public static List<string> AdminClaims { get; set; } = new List<string> { "Add User", "Edit User", "Delete User" }; }
This is normal?
Final note. I also see on the Internet the concept of βRole Claim,β which is explained in this blog post: http://benfoster.io/blog/asp-net-identity-role-claims
What is it? If I were not confused enough, now there is a third way to authorize users. Is this the best way to use roles as claims?