asp.net-mvc-4form-authentication

Mvc4 FormsAuthentication issue while using it in multiple websites


I am developing two different web sites. In that I have used FormsAuthentication for authentication. I am using following code

FormsAuthenticationTicket authTicket = default(FormsAuthenticationTicket);
HttpCookie authCookie = default(HttpCookie);

authTicket = new FormsAuthenticationTicket(1, user.userContext.UserName, DateTime.Now, DateTime.Now.AddMinutes(Session.Timeout), model.RememberMe, model.Email);
string strEncryptedTicket = FormsAuthentication.Encrypt(authTicket);
authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);
if (authTicket.IsPersistent)
{
    authCookie.Expires = authTicket.Expiration;
}
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);;
Session.Add(Constants.LOGIN_DO, user.userContext);

I am using same code in both sites to login. When login to one site it works. But if I open other site on same browser and try to login then it create problem. It misbehaves - like when I logout from site1 it also logout from site2 also. Suppose first site is www.someone.com and second site is something.someone.com.

Note: for site2 I am changing value Session.Add(Constants.LOGIN_DO, user.userContext); where LOGIN_DO = "OrgLoginDO";

web.config

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

I am not getting why this is happening? Can someone help me to solve this? do I need to use something different? I want to implement it like without Single Sign on.


Solution

  • To avoid collisions between the forms authentication cookies of the two sites you could give them different names:

    <authentication mode="Forms">
        <forms loginUrl="~/Account/Login" timeout="2880" name="SITE1COOKIE" />
    </authentication>
    

    and in your second site:

    <authentication mode="Forms">
        <forms loginUrl="~/Account/Login" timeout="2880" name="SITE2COOKIE" />
    </authentication>
    

    Also I can see that you are using ASP.NET Sessions. Make sure that you specify a different cookie name for the sessions as well:

    <sessionState cookieName="SITE1SESSION" ... />
    

    and:

    <sessionState cookieName="SITE2SESSION" ... />