rbasniak
rbasniak

Reputation: 4954

Adding user roles in runtime for ASP.NET Core API authorization

My API is using UseJwtBearerAuthentication and the HttpContext.User.IsAuthenticated has True on its value, so I can use [Authorize] on my controllers.

But now I want to use role based authentication, like [Authorize(Policy = "TestPolicy")]. I added the desired policies on my Startup.cs using AddAuthorization(...) extension.

The requests are returning code 403 (unauthorized), because the HttpContext.User.Identity.Roles is not populated.

I created a middleware to populate this property, and I can get the roles of the user with UserManager.GetRolesAsync(user). Now I have a list of user roles, but how can I add then to the curent HttpContext.User so the user could be authorized with the policies I added?

Upvotes: 0

Views: 1330

Answers (1)

adnan kamili
adnan kamili

Reputation: 9445

While creating jwt store role in the jwt as a claim, and create a permission requirement:

public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {

            if (context.User.HasClaim(c => c.Type == "role" && c.Value =
 requirement.Permission))
            {
                System.Console.WriteLine("User  has required permission: " + requirement.Permission);
                context.Succeed(requirement);
                return Task.CompletedTask;
            }
            System.Console.WriteLine("User is forbidden");
            return Task.CompletedTask;
        }
    }

checkout following for details:

https://github.com/adnan-kamili/AspNetCore-Web-Api-Rest-Starter-Kit

Upvotes: 1

Related Questions