Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Bypass ASP.NET unauthorized redirect to a login page

0.00/5 (No votes)
17 Mar 2009 1  
How to bypass ASP.NET unauthorized redirect to a login page.

Introduction

ASP.NET makes it easy to configure Forms Authentication and Authorization, including automatically redirecting you to the login page when necessary. The problem is that it also redirects authenticated users to the login page when they attempt to access pages that they are not authorized to access. This gives you the opportunity to login as someone else, and then be automatically redirected back to the page you originally attempted to access. But, that may not be the behavior you want for authenticated users -- do your users really have multiple logins, and do they understand why they end up back at the login page?

Lots of my system users contacted me about this behavior, they thought it is a bug and needs to be fixed!

The Solution

After lots of attempts, I found an acceptable approach (for me); it is all in the Global.asax Application_EndRequest event.

Protected Sub Application_EndRequest(ByVal sender As Object, ByVal e As System.EventArgs)
    Try
       'Check if the user is Authenticated and been redirected to login page
       If Request.IsAuthenticated  _
       And Response.StatusCode = 302  _
       And Response.RedirectLocation.ToUpper().Contains("LOGIN.ASPX") _
       Then
             ' check if the user has access to the page
            If Not UrlAuthorizationModule.CheckUrlAccessForPrincipal _
                                        (Request.FilePath, User, "GET") Then
                'Pass a parameter to the login.aspx page 
                FormsAuthentication.RedirectToLoginPage("errCode=401")
                
                'Or you can redirect him to another page like AuthenticationFaild.aspx
                'Response.Redirect("AuthenticationFaild.aspx")
            End If
        End If
    Catch ex As Exception
        'Do nothing
    End Try
End Sub

Basically, I check to see if the response is a redirect to the login page and if the user has already been authenticated. Finally, I check to see if the user does not have access from the original requested page. If all of those conditions are true, then I redirect them to the login page with parameters to indicate it's an authorization redirect.

Anyway, I hope this helps someone.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here