1

我在 mvc3 和 .net4 上使用了跨域 cookie 身份验证,它工作得很好,我在 mvc4 和 .net 4.5 上创建了另一个项目,并在 mvc 上从低版本复制/粘贴了我的代码(我的意思是 mvc4),现在我的在主域上创建身份验证cookie,但子域无法意识到用户已通过身份验证。

它是 mvc4 中的错误还是我必须启用一些期货或类似的东西?

我在主域上创建身份验证 cookie 的代码:

        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
          1,
           "fc5f06b006b44b05a257c406f4218638",//username
           DateTime.Now,
           DateTime.Now.AddDays(5),
           true,
           "members",
           FormsAuthentication.FormsCookiePath);

        // To give more security it is suggested to hash it
        string hashCookies = FormsAuthentication.Encrypt(ticket);
        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                                            hashCookies); // Hashed ticket
        cookie.Expires = DateTime.Now.AddDays(5);
        cookie.Domain = ".maindomain.com";
        Response.Cookies.Add(cookie);

在子域中使用这行代码来测试用户身份验证:

var result = System.Web.HttpContext.Current.User.Identity.IsAuthenticated + "-" +
                 System.Web.HttpContext.Current.User.Identity.Name;

在我的全球我有:

   protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        // look if any security information exists for this request
        if (System.Web.HttpContext.Current.User != null)
        {
            // see if this user is authenticated, any authenticated cookie (ticket) exists for this user
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                // see if the authentication is done using FormsAuthentication
                if (System.Web.HttpContext.Current.User.Identity is FormsIdentity)
                {
                    // Get the roles stored for this request from the ticket
                    // get the identity of the user
                    FormsIdentity identity = (FormsIdentity)System.Web.HttpContext.Current.User.Identity;
                    // get the forms authetication ticket of the user
                    FormsAuthenticationTicket ticket = identity.Ticket;
                    // get the roles stored as UserData into the ticket 
                    string[] roles = ticket.UserData.Split(',');
                    // create generic principal and assign it to the current request
                    System.Web.HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
                }
            }
        }
    }

在我的网络配置中:

  <authentication mode="Forms">
     <forms domain=".maindomain.com" name="atnc"  
      loginUrl="~/home" timeout="120" requireSSL="false" />
  </authentication>
4

0 回答 0