如何在登录cookie中保存用户ID

本文关键字:保存 用户 ID cookie 登录 | 更新日期: 2023-09-27 17:53:09

使用手动登录到web应用程序,

FormsAuthentication.SetAuthCookie(_username, true);

如何保存userID(一个整数值(及其cookie?

如何在登录cookie中保存用户ID

FormsAuthenticationTicket具有占用string userData的过载。在这里,除了默认的HttpContext.User.Identity(通常是电子邮件地址,例如使用SetAuthCookie登录的地址(之外,您还可以将其他数据添加到需要保存的加密cookie中。

所以你可以这样做:

    var user = new User { UserId = 1, Nickname = "Foo" };
    var encodedTicket = FormsAuthentication.Encrypt(
       new FormsAuthenticationTicket(
          1, 
          user.Nickname, 
          DateTime.Now,  
          DateTime.UtcNow.Add(FormsAuthentication.Timeout),
          true,                                                                            
          user.ToString()));
var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encodedTicket);
httpResponseBase.Cookies.Add(httpCookie);

您可以在User对象上ovveride ToString()方法来持久化该信息(例如,作为分隔字符串(。

然后,当您解密cookie时,拆分字符串并提取每个请求所需的信息。

使用FormsAuthentication.GetAuthCookie

HttpCookie httpCookie = FormsAuthentication.GetAuthCookie(_username, true); 
httpCookie["ID"] = userID.ToString();

身份验证方案中使用的用户名不一定意味着用户的登录名或实际用户名。它本质上意味着任何可以识别用户的字符串-通常,在表单身份验证的情况下,会使用登录名(因为登录名是唯一的(,但您可以使用用户id(或登录名和用户id的组合,例如"2|jack"(-只需记住您使用的任何值作为"用户名",相同的值将用作用户身份(HttpContext.User.Identity.Name(。