繁体   English   中英

如何在 ASP.NET Core 中设置运行时认证?

[英]How to set runtime authentication in ASP.NET Core?

我正在创建一个应用程序,其中有基于角色的模块管理,并且随时更改。 设想:

  • 如果用户有权创建和查看员工,则用户只能创建和查看员工,但将来管理员将用户的角色从创建和查看更改为查看和删除,则用户只能执行该活动。

我尝试使用[Authorize(Roles ="Staff")]但如果管理员更改运行时,则它不受管理。

任何人都可以调查一下并回复我吗?

这是一个复杂的问题,没有正确的答案,但有几种方法可以做到。 首先,我假设您使用基于声明的 jwt 使用无状态身份验证,最简单的方法是编写您自己的策略,该策略将在每次请求之前读取用户角色,这是最简单的方法,也是最快的实现方法。

internal class DatabaseRoles : IAuthorizationRequirement
    {
        public string Role { get; }

        public DatabaseRoles(string role)
        {
            Role = role;
        }
    }

    internal class DatabaseRolesHandler : AuthorizationHandler<DatabaseRoles>
    {
        private readonly UserManager<IdentityUser> userManager;

        public DatabaseRolesHandler(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            this.userManager = userManager;
        }

        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, DatabaseRoles requirement)
        {
            //NOTE this is the out of the box implementation of roles and simple query to get the roles from the EF backed database. I would recoment makeing a custom privelages store for this and not using roles for this but access rights
            var user = await userManager.FindByIdAsync(userManager.GetUserId(context.User));
            if (await userManager.IsInRoleAsync(user, requirement.Role))
            {
                context.Succeed(requirement);
            }
        }

    }

但是这个解决方案并不是那么高效,因为它需要在每个请求上调用数据库。 这在小负载上很好,但可能会造成流量问题。 另一种方法是在角色更改时重新调用所有用户令牌,但这非常复杂。 我敢肯定,如果您为 redis 之类的角色创建一些快速访问存储,那么每次调用都不会出现问题。 此外,我不建议您创建自己的用户存储,因为维护和更新安全标准是一场噩梦。

如果您使用 Session/Cookie 来存储登录的用户详细信息,您可以在管理员更改角色时清空详细信息。 在每个操作中,您都可以检查 Session/Cookie 中的角色并继续前进。 现在,只要用户点击屏幕上的任意位置,就会点击 controller。 将检查条件并注销用户,因为 Session/Cookie object 为空。

暂无
暂无

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

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