Efficiently check role claim

Clash Royale CLAN TAG#URR8PPP
Efficiently check role claim
I'm developing an Asp.NET MVC5 web application (.NET 4.6) and I need to show some extra lines of HTML to a group of users with a specific claim. I've seen some verbose solutions but I prefer to keep it short, so I came up with this
@
if (System.Security.Claims.ClaimsPrincipal.Current.Claims.ToList().FirstOrDefault(c => c.Type == "role" && c.Value == "AwesomeUserRole") != null)
<!-- my HTML goes here -->
Is it a good way to check for an authenticated user claim or is there a best practice to follow? Any cleaner / more efficient solution is welcome as well.
2 Answers
2
Because all Identity objects in ASP.NET are now a ClaimsIdentity, you could always cast the current IPrincipal to a ClaimsIdentity:
Identity
ClaimsIdentity
IPrincipal
ClaimsIdentity
((System.Security.Claims.ClaimsIdentity)User.Identity).HasClaim("role", "AwesomeUserRole")
But it is actually easiest to just use User.IsInRole("AwesomeUserRole")
User.IsInRole("AwesomeUserRole")
As long as you haven't changed the default configuration, claims with the type of role are automatically fed into the roles collection for the thread principal.
role
If you need to check for additional claim types besides roles, I usually create a set of extension methods for IPrincipal that wrap the claim checks:
IPrincipal
public static bool CanDoX(this IPrincipal principal)
return ((ClaimsIdentity)principal.Identity).HasClaim(claimType, claimValue);
The benefit of the extension method is that you can check for any kind of claim and return any values they may contain, not just whether or not the claim exists.
Check that the Identity is using "role" as its role claim type, the default is a uri
– Paul Hatcher
Dec 13 '16 at 13:07
Bear in mind that a Principal can have more than one identity associated with it, e.g. you have authenticated with Windows Authentication, but then added a custom identity with claims from your database.
So any claim check potentially needs to look at all identities, here's a couple of extension methods that will help
public static bool ClaimExists(this IPrincipal principal, string claimType)
var ci = principal as ClaimsPrincipal;
if (ci == null)
return false;
var claim = ci.Claims.FirstOrDefault(x => x.Type == claimType);
return claim != null;
public static bool HasClaim(this IPrincipal principal, string claimType,
string claimValue, string issuer = null)
x.Issuer == issuer));
return claim != null;
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
((System.Security.Claims.ClaimsIdentity)User.Identity).HasClaim("role", "miAdmin") and User.IsInRole("miAdmin") don't return the same value for me. The first is correct for me. Not sure why User.IsInRole("miAdmin") isn't working.
– RayLoveless
Dec 12 '16 at 18:53