Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

c# - ASP.NET Core Authorize AD Groups through web.config

In my old .NET MVC app, I could enable Windows Authentication in IIS and disable anonymous. Then in my web.config file I just had to put in this:

<authorization> 
  <allow roles="DomainMyADGroupToHaveAccess" />
  <deny users="*" /> 
</authorization> 

In .NET Core 2.0 this will not work – it denies anonymous correctly, but it authorizes all users no matter what.

If I do this:

[Authorize(Roles = "Domain\MyADGroupToHaveAccess")]

on my HomeController, it works, but I don't want to hardcode this setting in my project as it's something that needs to be changed for other environments.

How can I make web.config to work with AD Authorization? Or is there another way to not hardcode this setting in ASP.NET Core?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I solved this by making it into a policy which is able to call appsettings.json. This way other people who have access to the server can then edit the group to their own.

In Startup.cs:

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

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

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

In appsettings.json (or perhaps appsettings.production.json if you have different):

"SecuritySettings": {
  "ADGroup": "YourDomain\YourADGroup"
}

In your controllers you can then decorate it with this attribute:

[Authorize(Policy = "ADRoleOnly")]

Hope this can help other people

I have still to figure out how to apply this policy globally, so I don't have to authorize every controller, I'd figure it can be done in the services.AddMvc somehow?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...