绕过 ASP.NET 未授权重定向到登录页面
如何绕过 ASP.NET 未授权重定向到登录页面。
引言
ASP.NET 使得配置表单身份验证和授权变得容易,包括在必要时自动重定向到登录页面。问题在于,它也会将已身份验证的用户重定向到登录页面,当他们尝试访问他们无权访问的页面时。这给你一个机会以其他人的身份登录,然后自动重定向回你最初尝试访问的页面。但是,这可能不是你希望已身份验证用户所看到的行为——你的用户真的有多个登录名吗?他们是否理解为什么最终会回到登录页面?
很多我的系统用户联系我,关于这种行为,他们认为这是一个错误,需要修复!
解决方案
经过多次尝试,我找到了一种可接受的方法(对我而言);它全部在 Global.asax 的 Application_EndRequest
事件中。
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
基本上,我检查响应是否重定向到登录页面,以及用户是否已经过身份验证。最后,我检查用户是否没有从原始请求页面获得访问权限。如果所有这些条件都为真,那么我就将他们重定向到登录页面,并带有参数以指示这是一个授权重定向。
无论如何,我希望这能帮助到某人。