简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM