Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 372
Naigel Avatar asked Jan 29 '16 14:01

Naigel


People also ask

What is the difference between a role and a claim?

In Role-based authorization, applications enforce access by roles. These roles can be used in authorized attributes in your code. Alternatively, claims-based authorization enforces permissions by using information about the user rather than relying on a single role declaration.

What is role of claims?

A Role Claim is a statement about a Role. When a user is a member of a role, they automatically inherit the role's claims. An example of where this feature could be used is for handling application permissions. Roles provide a mechanism to group related users.

What is claim C#?

A claim is a name value pair that represents what the subject is, not what the subject can do. For example, you may have a driver's license, issued by a local driving license authority. Your driver's license has your date of birth on it.

What is Role-based authentication in ASP net?

Role-based authorization checks specify which roles which the current user must be a member of to access the requested resource. For example, the following code limits access to any actions on the AdministrationController to users who are a member of the Administrator role: C# Copy.


1 Answers

Because all Identity objects in ASP.NET are now a ClaimsIdentity, you could always cast the current IPrincipal to a ClaimsIdentity:

((System.Security.Claims.ClaimsIdentity)User.Identity).HasClaim("role", "AwesomeUserRole")

But it is actually easiest to just use 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.

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:

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.

like image 190
Jimmie R. Houts Avatar answered Sep 20 '22 07:09

Jimmie R. Houts