Search code examples
c#asp.netasp.net-authorization

Getting allow users from web.config


I tried to getting an allowed users from web.config to access the application and deny others and redirect them to another page. Here my code:

Config

<authentication mode="Windows"/>
<authorization>
  <allow users="anwar,abdulaziz"/>
  <deny users="?"/>
</authorization>

Code

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)
        {
            Response.Redirect("UnauthorizedUsers.aspx");
        }
    }
}

Solution

  • From what I understand, you want to redirect unauthorized users to another page.

    protected void Application_EndRequest(Object sender, EventArgs e)
    {
        if (HttpContext.Current.Response.Status.StartsWith("401"))
        {
            HttpContext.Current.Response.ClearContent();
            Response.Redirect("UnauthorizedUsers.aspx");
        }
    }