如何在asp.net的web.config位置路径中添加和删除授权用户
本文关键字:添加 路径 删除 用户 授权 位置 config asp net web | 更新日期: 2023-09-27 18:28:40
我正在尝试以编程方式从web.config中添加和删除授权用户。我正在使用Windows身份验证。
这是我在web.config 上看到的
<location path="Admin">
<system.web>
<authorization>
<allow users="domain'user1, domain'user2"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
现在,在代码中,我有以下代码。
protected void UpdateUsers()
{
System.Configuration.Configuration config = (Configuration)WebConfigurationManager.OpenWebConfiguration("~");
ConfigurationLocationCollection section = config.Locations;
foreach (ConfigurationLocation location in section)
{
if(location.Path == "Admin")
{
AuthorizationSection admin_section = (AuthorizationSection)config.GetSection("system.web/authorization");
AuthorizationRule thisAuth = new AuthorizationRule(AuthorizationRuleAction.Allow) ;
thisAuth.Users.Add("domain''username");
admin_section.Rules.Add(thisAuth);
admin_section.CurrentConfiguration.Save();
}
}
}
上面的代码是在system.web上添加部分,而不是在管理位置。
我找到了答案。这是更新后的代码。
protected void UpdateUsers()
{
Configuration config = (Configuration)WebConfigurationManager.OpenWebConfiguration("~");
AuthorizationSection root_section = (AuthorizationSection)config.GetSection("system.web/authorization");
//Remove all Current Users to root location.
root_section.Rules.Clear();
//Add New Users to root location.
AuthorizationRule rootAuth = new AuthorizationRule(AuthorizationRuleAction.Allow);
rootAuth.Users.Add("domain''rootusername1");
rootAuth.Users.Add("domain''rootusername2");
rootAuth.Users.Add("domain''rootusername3");
root_section.Rules.Add(rootAuth);
////Add Deny All Users to root location.
AuthorizationRule rootDeny = new AuthorizationRule(AuthorizationRuleAction.Deny);
rootDeny.Users.Add("*");
root_section.Rules.Add(rootDeny);
root_section.CurrentConfiguration.Save();
//Other Locations
ConfigurationLocationCollection section = config.Locations;
foreach (ConfigurationLocation location in section)
{
if (location.Path == "admin") //This is case Sensitive
{
Configuration adminConfig = (Configuration)location.OpenConfiguration();
AuthorizationSection admin_section = (AuthorizationSection)adminConfig.GetSection("system.web/authorization");
//Remove all Current Users to admin location.
admin_section.Rules.Clear();
////Add New Users to admin location.
AuthorizationRule adminAuth = new AuthorizationRule(AuthorizationRuleAction.Allow);
adminAuth.Users.Add("domain''adminusername1");
adminAuth.Users.Add("domain''adminusername2");
adminAuth.Users.Add("domain''adminusername3");
adminAuth.Users.Add("domain''adminusername4");
admin_section.Rules.Add(adminAuth);
adminAuth = null;
////Add Deny All Users to root location.
AuthorizationRule adminDeny = new AuthorizationRule(AuthorizationRuleAction.Deny);
adminDeny.Users.Add("?"); // For some reason if I remove this line it says "Object reference not set to an instance of an object"
adminDeny.Users.Add("*");
admin_section.Rules.Add(adminDeny);
admin_section.CurrentConfiguration.Save();
}
}
}
希望这对某人有帮助。