【问题标题】:How do I build a custom role based authorization in ASP Core 2?如何在 ASP Core 2 中构建基于角色的自定义授权?
【发布时间】:2017-11-15 00:30:31
【问题描述】:

我有一个数据库,其中包含一个用户表、访问表和一个连接表,将用户分配给多个访问权限。该站点将通过将 AD 中的身份用户名与用户表中的用户名匹配来验证用户,以验证他们可以看到该站点(Intranet)。访问表用于指定允许访问哪些页面。

在 ASP Core 2 中,我如何使用授权在启动时执行相同的检查,以验证它们是否在用户表中,然后更进一步并使用角色来允许用户访问特定网页。

我已经浏览了文档,但我不知道应该采用哪种方式,因为示例使用的登录名在我使用 AD 的情况下是不必要的。

我有一个 users 表并且不使用 AD 角色,因为我们有一个用于交换的管理员,而我无权访问它。

提前致谢

【问题讨论】:

    标签: c# asp.net asp.net-core


    【解决方案1】:

    Authorize 属性是您正在寻找的。例如,

    [Authorize(Roles = "Admin, User")]
    

    如果您使用 OAuth 进行身份验证,您将在身份验证时创建一个 ClaimsIdentity。根据声明,Authorize 属性将开箱即用。例如,

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
    
            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
    
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
    
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
    
            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(oAuthIdentity);
        }
    

    你可以参考this post,这里我已经更详细地解释了类似的场景。

    【讨论】:

    • 我将如何对此进行扩展并使用数据库调用来匹配登录到用户表中的用户名的 Active Directory 用户名?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    • 2014-10-22
    • 1970-01-01
    相关资源
    最近更新 更多