I am trying to move away from WebForms and learn MVC, specifically using the new ASP.NET Identity model. However, I cant seem to find any formal documentation from Microsoft, that demonstrates how to create a claims object, and store it in a database for a authenticated user.
My site, needs to do the following:
Can anyone shed any light on how this can be achieve?
Honestly, I'm still learning the ropes with Identity, myself. Admittedly, the Microsoft provided documentation could be better, but I've never found any of their documentation all that helpful. The best stuff always comes from the community, and unfortunately, Identity is still so new that the community has had time to really flesh it out yet.
That said, here's what I know, with the understanding that there may be better ways that I'm simply not aware of, yet.
Your UserManager
has three methods of significance: GetClaimsAsync
, AddClaimAsync
and RemoveClaimAsync
.
To get all claims for a user:
var claims = await UserManager.GetClaimsAsync(userId);
You can get the current user's id with:
var userId = User.Identity.GetUserId();
Once you have the claims, to pull out a specific one:
var someClaim = claims.FirstOrDefault(c => c.Type == "SomeClaimType");
Where "SomeClaimType" is the name of the claim as it was added. In some scenarios this might be a fully qualified URN, or it may just be a simple string. If it's not something you personally added, the best thing to do is just inspect the claims
variable during a debug session to see what you actually have there.
Also, since the list of claims is a queryable, you can pretty much do whatever LINQ query you want on it, Where
, Count
, etc.
To add a new claim:
await UserManager.AddClaimAsync(userId, new Claim("SomeClaimType", claimValue));
And to remove a claim:
await UserManager.RemoveClaimAsync(userId, someClaim);
Roles work in a similar way. To get all roles for a user:
var roles = await UserManager.GetRolesAsync(userId);
To see if a user is in a particular role:
var hasRole = await UserManager.IsInRoleAsync(userId, "SomeRole");
To add a user to a particular role:
await UserManager.AddToRoleAsync(userId, "SomeRole");
And to remove:
await UserManager.RemoveFromRoleAsync(userId, "SomeRole");
Adding the roles in the first place is a bit different; you have to create an instance of RoleStore
.
var roleStore = new RoleStore<IdentityRole>(context);
Then, you can use that to manage all roles. For example, to create a new role:
await roleStore.CreateAsync(new IdentityRole("RoleName"));
To remove:
var identityRole = await roleStore.FindByNameAsync("RoleName");
await roleStore.DeleteAsync(identityRole);
Getting all roles, is not possible with the Identity-specific API at this time, but you can always fall back to querying with Entity Framework directly:
var allRoles = context.Roles.OrderBy(o => o.Name);