3

I am using ASP.NET and I want to be able to redirect user to another page from web config.

I have number of restrictions like:

 <location path="Structures.aspx">
    <system.web>
      <authorization>
        <allow roles="Admin"/>
        <deny users="*" />
      </authorization>
    </system.web>
  </location>

And it will be great if I redirect user to some page. I saw this post but it's not what I was looking for.

I need to do it in web.config and not in code behind. Thanks!

Community
  • 1
  • 1
makambi
  • 769
  • 1
  • 13
  • 22

2 Answers2

5

Assuming you want to handle all "Unauthorized" errors:

<customErrors defaultRedirect="Error.aspx" mode="On">
    <error statusCode="401" redirect="Unauthorized.aspx" />
    <error statusCode="403" redirect="Forbidden.aspx" />
</customErrors>

Any 401 (unauthorized) requests will be forwarded to Unauthorized.aspx.

alternatively, you'll need to perform the check in your Page_Load event. If this seems tedious you can always create a base page class for all pages that are supposed to be admin-only and perform the check there. e.g.

// base class
public class AdminOnlyPage : Page
{
  /*...*/ Page_Load(Object sender, EventArgs e)
  {
    /* check if the user is admin otherwise reject and redirect */
  }
}

// Your "Structures.aspx" page
public class Structures : AdminOnlyPage
{
}
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • thanks, I have to many roles to manage to use code behind approach. each page has it's own role that it accepts) customError resolution looks much better. i will try – makambi Feb 06 '13 at 14:57
  • unfortunately adding customErrors did not help in my case on error it redirects to Error.aspx, but on user is not allowed to see page by his role it still redirects me to Default.aspx For example for response is: HTTP/1.1 302 Found Location: /Default.aspx?ReturnUrl=%2fStructures.aspx – makambi Feb 07 '13 at 11:49
2

I noticed my app is redirecting back to login page using "302 Found" code with "Location" header set. Since my login page happens to be in external application that just shares the same server, I couldn't modify it.

Instead, I added this to my global.asax:

    protected void Application_EndRequest(Object sender, EventArgs e)
    {
        if (Response.Status.StartsWith("302") 
            &&
            Request.IsAuthenticated 
            &&
            Response.RedirectLocation != null 
            &&
            Response.RedirectLocation.StartsWith(System.Web.Security.FormsAuthentication.LoginUrl)
        ) {
            //log.Trace("Preventing redirection from app to login form since user is already logged in. It's authorization issue, not authentication.");
            Response.Clear();
            Response.Redirect("~/AccessDenied.aspx");
        }
    }
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
Ekus
  • 1,679
  • 21
  • 17