Redirect user to another page from web.config when his role has not enough permission

ⅰ亾dé卋堺 提交于 2019-12-06 04:14:39

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
{
}

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