asp.net How do I reference authorized users hard coded in web.config in my code

给你一囗甜甜゛ 提交于 2019-12-11 13:16:21

问题


I am building a website on an intranet and one of the directories can only be accessed by hard coded authorized users. They are defined in web.config. It looks similar to this.

<location path="admin">
    <system.web>
        <authorization>
            <allow users="user1"/>
            <allow users="user2"/>
            <allow users="user3"/>
            <allow users="user4"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</location> 

What I want then is to create a link to this directory which only appears to those users... At the moment, to build the link I'm rechecking there windows usernames and hard coding them in again like this...

<% 
    if (HttpContext.Current.User.Identity.Name == "user1" ||         
        HttpContext.Current.User.Identity.Name == "user2" ||
        HttpContext.Current.User.Identity.Name == "user3" ||
        HttpContext.Current.User.Identity.Name == "user4")
    {
        Response.Write("<a href='admin/Default.aspx'>Admin Site</a>");
    }   
%>

But what I want to do is reference my list from the webiconfig file and say something like

if (HttpContext.Current.User.Identity.Name == // a user from the web.config list

Is this possible and if so can you help me... Thanks


回答1:


You can get the authorization rules from web.config like this:

            AuthorizationSection configSection =
      (AuthorizationSection)ConfigurationManager.GetSection("system.web/authorization");

        var users = new List<string>();

        var rules = configSection.Rules;

        foreach (AuthorizationRule rule in rules)
        {
            if (rule.Action == AuthorizationRuleAction.Allow)
            {
                foreach (string user in rule.Users)
                {
                    if (!users.Contains(user)) users.Add(user);
                }
            }
        }

But you must also pay atention to the precedence of the rules.



来源:https://stackoverflow.com/questions/11990606/asp-net-how-do-i-reference-authorized-users-hard-coded-in-web-config-in-my-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!