【问题标题】:How to use AD for authentication and use SQL database for authorization on .NET Core web app for Intranet如何使用 AD 进行身份验证并使用 SQL 数据库对 Intranet 的 .NET Core Web 应用进行授权
【发布时间】:2020-01-11 15:11:51
【问题描述】:

我有一个使用 Windows 身份验证的 MVC .NetCore 3.0 Web 应用程序,我想为 SQL 数据库上的每个用户添加角色/权限。我的想法是将他们的 AD 用户名与我创建的数据库表(用户、角色、权限)进行比较。如何才能做到这一点?我找到了用户创建自己帐户的文档,但没有找到任何使用 AD 的文档。

【问题讨论】:

    标签: sql active-directory asp.net-core-mvc role-base-authorization


    【解决方案1】:

    您可以使用IClaimsTransformation将您当前的windows身份验证用户与本地数据库用户关联,检查用户是否存在/角色/权限,您还可以将用户的自定义声明(例如角色)添加到 ClaimsPrincipal ,以便您可以以后直接从User.Claims获取属性:

    public class ClaimsTransformer : IClaimsTransformation
    {
        public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            var id = ((ClaimsIdentity)principal.Identity);
    
            var ci = new ClaimsIdentity(id.Claims, id.AuthenticationType, id.NameClaimType, id.RoleClaimType);
    
            //read database and create/check a user in local database , add custom claims  in Principal
            if (....)
            {
                ci.AddClaim(new Claim("localUserID", "XXX"));
            }
            else
            {
                ci.AddClaim(new Claim("localUserID", "XXXX"));
    
            }
    
    
            var cp = new ClaimsPrincipal(ci);
    
            return Task.FromResult(cp);
        }
    }
    
    
     services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
    

    【讨论】:

    • 我是 .NET Core 的新手,能否提供更多细节?我不明白 if 语句并添加新的声明。
    • 即代码示例,您所做的是使用 ef 查询数据库以检查用户/角色,如果您不想添加声明,则不需要添加声明。
    • 这正是我需要帮助的地方。设置后如何设置为使用 [Authorize(Roles="xxxx")] 属性?
    • 使用EF查询数据库:docs.microsoft.com/en-us/ef/core/get-started/?tabs=netcore-cli[Authorize(Roles="xxxx")] 将检查 ClaimsIdentity.RoleClaimType(schemas.microsoft.com/ws/2008/06/identity/claims/role) ,您的原则中是否有该声明?
    • 我没有这个要求。我必须使用 IdentityDbContext 才能工作吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 2018-08-09
    • 2017-04-08
    相关资源
    最近更新 更多