Wednesday, July 11, 2012

Getting FormsAuthentication to work inside iOS WebView

I developed a Facebook mobile web application and wanted users to easily access it by scanning a QR Code. However, while the web application works perfectly in Mobile Safari, it totally fails in the QR Code reader app and gets stuck in the landing page. First suspicion was Facebook’s login process. After extensive debugging, I could not nail the problem, as the code runs in the exact sequence as I wanted it to.

The only thing not behaving correctly is that this.User.Identity.IsAuthenticated always returns false. The other abnormally is that iOS WebView sends a user agent that does not contain the word Safari. Interestingly, the this.Request.Cookies collection contains the forms authentication cookie. That finally brought me to conclude that the problem lies in FormsAuthentication not recognizing the cookie. Luckily I found the answer on http://stackoverflow.com/questions/3605076/thread-currentprincipal-claims-incorrectly-to-be-anynomous.

By setting

<authentication mode="Forms">
  <forms cookieless="UseCookies" />
</authentication>

the web application works perfectly inside WebView. Hurray!

Scotts Hanselman recently blogged about the very same problem and offered another way to solve the problem http://www.hanselman.com/blog/FormsAuthenticationOnASPNETSitesWithTheGoogleChromeBrowserOnIOS.aspx. And the good news is that things will work out of the box starting from ASP.NET 4.5. Good job Scott!