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
If Request.IsAuthenticated _
And Response.StatusCode = 302 _
And Response.RedirectLocation.ToUpper().Contains("LOGIN.ASPX") _
Then
If Not UrlAuthorizationModule.CheckUrlAccessForPrincipal _
(Request.FilePath, User, "GET") Then
FormsAuthentication.RedirectToLoginPage("errCode=401")
End If
End If
Catch ex As Exception
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.