简体   繁体   English

ASP.NET Core 2 - AD 组未映射到安全角色

[英]ASP.NET Core 2 - AD Groups not mapping to security roles

I have been retrieving the username via User.Identity.Name, however I need a way to limit access to certain pages via groups in Active Directory.我一直在通过 User.Identity.Name 检索用户名,但是我需要一种方法来限制通过 Active Directory 中的组访问某些页面。

For example 'Domain Admins' can see all the pages and 'View Users' can only see the landing page and one other.例如,“域管理员”可以查看所有页面,而“查看用户”只能查看登录页面和其他页面。

In Startup.cs在 Startup.cs 中

services.AddAuthentication(IISDefaults.AuthenticationScheme);

            services.AddAuthorization(options =>
            {
                options.AddPolicy("AdminRoleOnly", policy => policy.RequireRole(Configuration["SecuritySettings:AdminGroup"]));
            });

            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();

                config.Filters.Add(new AuthorizeFilter(policy));
            });

Config:配置:

  "SecuritySettings": {
    "AdminGroup": "MYDOMAIN\\Domain Admins"
  }

On my page model (I do not have controllers):在我的页面模型上(我没有控制器):

[Authorize(Policy = "AdminRoleOnly")]
    public class RequestsModel : PageModel

I just get an error saying I am not authorised no matter what我只是收到一条错误消息,说无论如何我都没有获得授权

In the end I wrote a handler myself (with some help of another post):最后我自己写了一个处理程序(在另一篇文章的帮助下):

 public class CheckADGroupHandler : AuthorizationHandler<CheckADGroupRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       CheckADGroupRequirement requirement)
        {

        var groups = new List<string>();
        var wi = (WindowsIdentity)context.User.Identity;
        if (wi.Groups != null)
        {
            foreach (var group in wi.Groups)
            {
                try
                {
                    groups.Add(group.Translate(typeof(NTAccount)).ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }

            foreach (string policygroup in requirement.GroupName)
            {

                if (groups.Contains(policygroup))
                {
                    context.Succeed(requirement);
                }
            }
        }

        return Task.CompletedTask;
    }
}

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

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