Single Sign On via Cookie Sharing for Sub Domains using ASP.NET
July 30, 2010
Posted by on
ASP.NET supports Forms Based Authentication (FBA). FBA mandates that user logging to the site must have an .ASPXAUTH cookie. If the cookie stored on your computer is persistent it would bypass the login screen next time to access the site. This happens because every time you send a request out to a site, all the cookies stored for their site on your computer travel along with the corresponding HTTP request. Now this holds true not only for site per se, but also holds for any sub domains of that site. For e.g. if you have a persistent cookie stored for abc.com, the authentication cookie would not only be send to abc.com, but also xyz.abc.com and pqr.abc.com.
So the question comes how do set the domain name for an authentication cookie in ASP.NET? Pretty simple, use GetAuthCookie method of FormsAuthentication class.
HttpCookie httpCookie = FormsAuthentication.GetAuthCookie( “someuser”, true ); //Persistent Cookie
httpCookie.Domain = “somedomain.org”; // Set the domain
HttpContext.Current.Response.Cookies.Add( httpCookie ); // add the auth cookie to response
Response.Redirect( FormsAuthentication.GetRedirectUrl( “someuser”, true ) );
Note the second parameter passed to GetAuthCookie – ‘true’. This would create a persistent cookie. This cookie would be send to the sites in the same domain and so would bypass the login screen. Also it’s the machinekey which is used to generate (encrypt / decrypt) the authentication cookie. Hence, you need to ensure that machineKey is same for all the applications which are part of your SSO solution as shown below:
<machineKey validationKey=”64Bytes” decryptionKey=”24Bytes” decryption=”3DES” validation=”SHA1″/>
You can find more details about how to generate these keys with differences between decryptionKey (used for authentication ticket) and validationKey (used for viewstate) here.
Finally the GetAuthCookie code won’t work if the machine name where you are running the application and the domain name used don’t match. To do the same you might have to edit your ‘C:\Windows\System32\drivers\etc\hosts’ file and provide an alias. And that’s it. You are all set with your SSO solution.