When working with .NET forms authentication, I have found a strange behavior:
For example, we have a web site using form based authentication. There are only two pages in the site: login.aspx and default.aspx. Default.aspx is the protected page.
Without login to the site, if you type directly the URL to the default.aspx page with ReturnUrl as QueryString like this:
http://localhost/YourWebApp/Default.aspx?ReturnUrl=Default.aspx
Instead of redirect you to the login.aspx page, you will directly get http unauthorized error (401.2).
However, if you remove the ReturnUrl query string or change it to something else, you will get expected behavior: redirect to login.aspx page. It seems .NET has some special treatment to ReturnUrl parameter.
In order to fix this, we need to intercept the 401 response before it sends to client and redirect user to login.aspx page. In global.asax page, we need to add this event handler:
For example, we have a web site using form based authentication. There are only two pages in the site: login.aspx and default.aspx. Default.aspx is the protected page.
Without login to the site, if you type directly the URL to the default.aspx page with ReturnUrl as QueryString like this:
http://localhost/YourWebApp/Default.aspx?ReturnUrl=Default.aspx
Instead of redirect you to the login.aspx page, you will directly get http unauthorized error (401.2).
However, if you remove the ReturnUrl query string or change it to something else, you will get expected behavior: redirect to login.aspx page. It seems .NET has some special treatment to ReturnUrl parameter.
In order to fix this, we need to intercept the 401 response before it sends to client and redirect user to login.aspx page. In global.asax page, we need to add this event handler:
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
if (application.Response.StatusCode != 401 || application.Request.IsAuthenticated) return;
Response.Redirect(FormsAuthentication.LoginUrl);
}
Comments