Detect a security exception when using FormsAuthentication

If you are using the web.config to determine security for aspx pages, you may have noticed that you don’t get the chance to determine whether a security exception has been thrown.  The user will simply be return to the login page with a ReturnUrl query string pointing back to the url they were trying to access.

If you want to show the user a different screen (like an Access Denied screen or something like that), you need to add an HttpModule to the application and add a handler to the EndRequest event.  In there, you can check the Request has been authenticated and if the Response.RedirectLocation points back the login page with a ReturnUrl.

Here is some code for the EndRequest event that should help you out:

void context_EndRequest(object sender, EventArgs e)
{

    HttpContext Context = HttpContext.Current;
    HttpRequest Request = Context.Request;
    HttpResponse Response = Context.Response;

    if (Request.Url.AbsolutePath.EndsWith(".aspx", StringComparison.CurrentCultureIgnoreCase))
    {
        if (Request.IsAuthenticated    
            && ! string.IsNullOrEmpty(Response.RedirectLocation)
            && Response.RedirectLocation.IndexOf("login.aspx?ReturnUrl=", StringComparison.CurrentCultureIgnoreCase) != -1)
        {
            //they are logged in and getting redirected to the login page - this means that they don't have access to something
            Response.RedirectLocation = Response.RedirectLocation.ToLowerInvariant().Replace("login.aspx", "Errors/AccessDenied.aspx");
        }
        
    }
}

 

Hope that helps!

 

more later – joel

No Comments