I am trying to setup a very basic Forms authentication example.
It is correctly redirecting unauthenticated users to the login page and on submit verifying the credentials and if correct calling:
FormsAuthentication.RedirectFromLoginPage(username.Text, false);
If the user is one named in the authorization section they get their page. If not it bounces them back to the login page with no error.
How can I redirect correctly authenticated but unauthorized users to a specific error page or detect the authorization error to display an error message on the login page bounce back?
Here is my web.config
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="/forms/Login" />
</authentication>
<authorization>
<deny users="?" />
<allow users="username1, username2" />
<deny users="*" />
</authorization>
Update:
Based on the answers / comments / research I've got two working solutions.
Put the following in the Page_Load method of your Login form:
if (Request.IsAuthenticated && !string.IsNullOrEmpty(Request.QueryString["ReturnUrl"])) { // This is an unauthorized, authenticated request... Response.Redirect("FailedAuthorization.aspx"); }
OR
Put the following in your Global.aspx file:
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; } }
Thank you for all the help with this!