Friday, June 19, 2009

ASP.Net - Single Sign On

Task : As soon as user logs into the website, he remains logged in even if he move across sub domains.

eg. if user logged in to the website using www.domain.com, now via a link, he moves to subdomain.domain.com then he should not be required to re login.

Solution :

In order to achieve this, you need to take two actions,

1. Make the following changes in web.config :

Within System.web element, add the following,

<authentication mode="Forms">
<forms path="/" name=".cookieName" cookieless="UseCookies" domain=".domainname.com"/>

</authentication>

If your site's domain address is "www.sitename.com" then domain will be set as ".sitename.com"

2. Add the following code piece to the code which runs on logout,

HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];

if (cookie != null)

{

cookie.Domain = FormsAuthentication.CookieDomain;

cookie.Expires = DateTime.Now.AddDays(-360);

Response.Cookies.Add(cookie);

}

FormsAuthentication.SignOut();

If you use a single domain then it's not required that you explicitly expire the authentication cookie, a simple ForsmAuthentication.SignOut() should work fine, but once the cookie domain is set then you will need to expire the cookie explicitly, otherwise your user will remain logged in.

Once you have done both the actions, your job is done and your user's login should work for the main domain and all the sub domains.

Next Problem >> Though this solution will keep the user logged in but every time when he will move to a new sub domain, his session will renew, any information which you placed into the session at the time of logging in will be lost too. The informatino can be refilled but more than that it's a performance issue.

Let's discuss this in Part 2.

No comments:

Post a Comment