Is it possible to check if an ApplicationUser has a Claim?
I know it is possible to check if an ApplicationUser is in a role
userManager.IsInRoleAsync(applicationUser,"admin");
And i know it could be possible to check if a user has a Claim like this:
userManager.GetClaimsAsync(applicationUser)).Any(c=>c.Type == "userType" && c.Vaue == "admin");
But i'd like to use something like with a ClaimsPrincipal object:
User.HasClaim("userType", "admin");
But i don't have a ClaimsPrincipal, i just have the ApplicationUser. So i also would like to know the way of getting the ClaimsPrincipal of an ApplicationUser, if it is possible.
As @Jerodev answered you can use UserManager to get user claims. Alternatively, you can use your DbContext that is derived from IdentityDbContext<ApplicationUser>.
bool hasClaim = _db.UserClaims
.Any(c => c.UserId == userId && c.ClaimValue == claimValue && c.ClaimType == claimType);
Both techniques will work only for claims that are stored in DB and will not work for claims that you would add dynamically for example in UserClaimsPrincipalFactory. Thus, both techniques are not the same as User.HasClaim("userType", "admin") where User is ClaimsPrincipal
You could add the following extension method to your UserManager class:
public static bool HasClaim(this UserManager userManager, string type, string value)
{
return userManager.GetClaims(applicationUser).Any(c=>c.Type == type && c.Vaue == value);
}
Now you can use this method on your userManager object:
var isAdmin = userManager.HasClaim("userType", "admin");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With