ASP.NET Core 通过 web.config 授权 AD 组 [英] ASP.NET Core Authorize AD Groups through web.config
问题描述
在我的旧 .NET MVC 应用程序中,我可以在 IIS 中启用 Windows 身份验证并禁用匿名.然后在我的 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>
在 .NET Core 2.0 中这是行不通的——它正确地拒绝匿名,但无论如何它都会授权所有用户.
In .NET Core 2.0 this will not work – it denies anonymous correctly, but it authorizes all users no matter what.
如果我这样做:
[Authorize(Roles = "Domain\MyADGroupToHaveAccess")]
在我的 HomeController
上,它可以工作,但我不想在我的项目中硬编码此设置,因为它需要针对其他环境进行更改.
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.
如何使 web.config
与 AD 授权一起使用?或者是否有另一种方法可以不在 ASP.NET Core 中硬编码此设置?
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?
推荐答案
我解决了这个问题,把它变成了一个能够调用 appsettings.json
的策略.这样,其他有权访问服务器的人就可以编辑自己的组.
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.
在 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));
});
在appsettings.json
(或者appsettings.production.json
,如果你有不同的话):
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")]
希望这可以帮助其他人
我仍然需要弄清楚如何在全球范围内应用此策略,所以我不必授权每个控制器,我认为它可以在 services.AddMvc
中以某种方式完成?
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?
这篇关于ASP.NET Core 通过 web.config 授权 AD 组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!