我正在尝试设置一个非常基本的表单身份验证示例。
它正确地将未经身份验证的用户重定向到登录页面,并在提交验证凭据时正确调用:
FormsAuthentication.RedirectFromLoginPage(username.Text, false);
如果用户是授权部分中指定的用户,他们将获得他们的页面。如果不是,它会将它们弹回登录页面而没有错误。
如何将经过正确身份验证但未经授权的用户重定向到特定错误页面或检测授权错误以在登录页面反弹时显示错误消息?
这是我的 web.config
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="/forms/Login" />
</authentication>
<authorization>
<deny users="?" />
<allow users="username1, username2" />
<deny users="*" />
</authorization>
更新:
根据答案/评论/研究,我有两个可行的解决方案。
将以下内容放入登录表单的 Page_Load 方法中:
if (Request.IsAuthenticated && !string.IsNullOrEmpty(Request.QueryString["ReturnUrl"])) { // This is an unauthorized, authenticated request... Response.Redirect("FailedAuthorization.aspx"); }
或者
将以下内容放入 Global.aspx 文件中:
protected void Application_EndRequest(object sender, EventArgs e) { if (Response.StatusCode == 401) { //Use the built in 403 Forbidden response Response.StatusCode = 403; //OR redirect to custom page //Response.Redirect("FailedAuthorization.aspx"); } } protected void Application_AuthenticateRequest(object sender, EventArgs e) { if (Request.IsAuthenticated) { // Requires ASP.NET >= 4.5 Response.SuppressFormsAuthenticationRedirect = true; } }
感谢您为此提供的所有帮助!