创建持久性身份验证cookie的问题:ASP.NET MVC

时间:2010-11-05 20:04:05

标签: asp.net asp.net-mvc-2 authentication forms-authentication

好的,这是我创建身份验证cookie的代码:

        // get user's role
        List<UserType> roles = rc.rolesRepository.GetUserRoles(rc.userLoginRepository.GetUserID(userName));
        List<string> rolesList = (from r in roles
                                 select r.ToString()).ToList();
        string[] rolesArr = rolesList.ToArray();

        // create encryption cookie
        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                1,
                userName,
                DateTime.Now,
                DateTime.Now.AddDays(90),
                createPersistentCookie,
                String.Join(";",rolesArr) //user's roles 
                );

        // add cookie to response stream
        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

        System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
        System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
        //FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);

这是我在Global.asax中的代码,用于将用户角色设置为用户身份:

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie == null || authCookie.Value == "")
        {
            return;
        }
        FormsAuthenticationTicket authTicket = null;
        try
        {
            authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            string[] roles = authTicket.UserData.Split(new char[] { ';' });
            if (Context.User != null)
            {
                Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
            }
        }
        catch
        {
            return;
        }
    }

但是,如果顶部示例中的“createPersistentCookie”为TRUE,则不会创建持久性cookie。如果我像这样取消注释最后一行:

        //System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);
        FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);

然后在我的硬盘上创建持久性cookie。但是在Global.asax代码中,“authTicket”中的UserData字段是空白的,所以我无法正确设置角色!

所以我必须使用SetAuthCookie来创建一个持久性cookie,但由于某种原因,UserData字段会从持久性cookie中消失。

这是什么答案?

1 个答案:

答案 0 :(得分:17)

要创建持久性cookie,您需要设置Expires属性:

if (authTicket.IsPersistent)
{
    authCookie.Expires = authTicket.Expiration;
}