Software Twist – Adrian Tosca Blog

The infamous RedirectFromLoginPage method

Posted in Software Development by Adrian Tosca on 2009, February 28

Do you happen to spent a lot more time than you expect on tasks that seemed simple enough? It happen to me. Last night. 3 more hours than expected.

The task was to add custom forms authentication to a web application I work on. I didn’t pay to much attention to the authentication as it was more important to first settle down the functional aspects of the application. But the time to do it has finally arrived. The plan was simple:

  1. Add a custom user class implementing the IPrincipal interface
  2. Add an encrypted cookie containing the serialized user data
  3. Check the cookie on AuthenticateRequest Event and set the custom user instance on HttpContext.Current.User

But something went wrong at point 2. The cookie just didn’t want to go to the browser. The code looks clear enough:

Response.Cookies.Add(new HttpCookie(userName, encryptedTicket));
FormsAuthentication.RedirectFromLoginPage(userName, false);

As I discovered (hours later if you recall) is that the RedirectFromLoginPage method does not do just what it says. I mean what would you expect to do. It just says ‘redirect from login page‘ isn’t it? It will do a redirect to the login page… well, not quite, as the MSDN documentation says:

If the CookiesSupported property is true, and either the ReturnUrl variable is within the current application or the EnableCrossAppRedirects property is true, then the RedirectFromLoginPage method issues an authentication ticket and places it in the default cookie using the SetAuthCookie method.

Yeap, that’s right, the method was overriding my cookie with an empty (but valid) one. After reading this, it was a simple fix:

Response.Cookies.Add(new HttpCookie(userName, encryptedTicket));
Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, false));

There are a couple of lessons to learn from this experience:

  • Read the f…(snip) documentation.
  • Always check the assumptions, even the ones that look obvious true. 
  • Don’t do like them. The RedirectFromLoginPage does two things (redirects and sets a default cookie) breaking the separation of concern principle.
Tagged with: ,

Comments Off on The infamous RedirectFromLoginPage method

%d bloggers like this: