Proper way to assess Role in Authorization as User.IsInRole() always returns false

Charles de M.

A lot has been asked around the User.IsInRole, but I cannot find the right answer.

I need to validate a certain role, by using an AuthorizationHandler (through a authorizationrequirement)

I have a ASP.NET Core 2.1 project, whith Individual User Accounts. I have seeded the database and added the user to a (one role) role using userManager.AddToRoleAsync and, yes, the database shows the users, the roles and connection between them.

I have created a CandidateViewHandler that controls the authorization for a View-Contorller. IT looks as follows

public class CandidateViewHandler : AuthorizationHandler<ViewCandidateRequirement, Candidate>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ViewCandidateRequirement requirement, Candidate resource)
    {
        if (context.User.Identity.IsAuthenticated)
        {
            if (resource.Email == context.User.FindFirst(ClaimTypes.Name).Value)
            {
                context.Succeed(requirement);
            }
            else
            {
                bool IsAdmin = context.User.IsInRole("Administrator");
                bool IsSearch = context.User.IsInRole("Searcher");                    
                if (IsAdmin == true || IsSearch == true)
                {
                    context.Succeed(requirement);
                }
            }
        }
        return Task.CompletedTask;
    }
}

However, IsAdmin and IsSearch always return false. Even when testing it in the controller, the results remain the same. Should I use Claims in 2.1? And if so, how?

Ruard van Elburg

What the discussion, mentioned by Charles de M., IMO actually shows is that roles are in fact an unnecessary addition to identity. Seems to me that for the future it would be better to remove the AspNetRoles table (or at least not to use it anymore) and use roles as claims directly, instead of having identity to add the roles as claims.

Add your role type claims to the AspNetUserClaims table. The default role claim type is http://schemas.microsoft.com/ws/2008/06/identity/claims/role. Any claim of that type should automatically be mapped as role so it can be used with IsInRole.

You can also use custom mapping in the client:

services.AddAuthentication()
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
            {
                RoleClaimType = "role",
                NameClaimType = "name",
            };
    });

A side note, you may consider to not use roles at all any more, as asp.net core has many, more advanced features which you can use for authorization.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

User.IsInRole always returns false in View or code using Policy based Authorization

User.IsInRole always returns false with Token Authentication

User.IsInRole() always returns false only in controller

ASP.NET Core Identity 2: User.IsInRole always returns false

MVC 4: User.IsInRole() returns false after logout

ASP.NET Core Custom Role Based Authorization (Custom User.IsInRole)?

Can't check user role. User.IsInRole returning false

password_verify Always Returns False, even with proper variables used

IsInRole return false even if there is role in claims

User.IsInRole return false

Why does @User.IsInRole always return false in _Layout.cshtml

what is the proper way of figuring out if an sql statement returns true or false?

asp.net core 2.0 windows role based authorization always returns 403

User.IsInRole() returns false and Authorize Roles gives me an Access Denied

getRequestProperty("Authorization") always returns null

user.is_authenticated always returns False for inactive users on template

SignInManager.IsSignedIn(User) method always returns false

Contains always returns false

isEqualToString always returns False

hasNextLine() always returns false

isHardwareAccelerated() always returns false

Always returns false

StrPos always returns False?

Role added to HttpContext.current.user but isInRole(rolename) is not working

wso2 indentity server 5.10.1 - role-based adaptive user authentication var hasRole is always false

Regex matches always returns false

RegEx matcher always returns false

python if statement always returns False

Testing a path always returns False