简体   繁体   English

在运行时中为ASP.NET Core API授权添加用户角色

[英]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. 我的API使用UseJwtBearerAuthentication ,并且HttpContext.User.IsAuthenticated的值为True ,因此可以在控制器上使用[Authorize]

But now I want to use role based authentication, like [Authorize(Policy = "TestPolicy")] . 但是现在我想使用基于角色的身份验证,例如[Authorize(Policy = "TestPolicy")] I added the desired policies on my Startup.cs using AddAuthorization(...) extension. 我使用AddAuthorization(...)扩展名在Startup.cs上添加了所需的策略。

The requests are returning code 403 (unauthorized), because the HttpContext.User.Identity.Roles is not populated. 由于未填充HttpContext.User.Identity.Roles,因此请求返回的code 403 (未经授权)。

I created a middleware to populate this property, and I can get the roles of the user with UserManager.GetRolesAsync(user) . 我创建了一个中间件来填充此属性,并且可以使用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? 现在,我有一个用户角色列表,但是如何将其添加到当前的HttpContext.User以便可以使用添加的策略对用户进行授权?

While creating jwt store role in the jwt as a claim, and create a permission requirement: 在创建jwt时将角色存储在jwt中作为声明,并创建权限要求:

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 https://github.com/adnan-kamili/AspNetCore-Web-Api-Rest-Starter-Kit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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