How can I create persistent cookies in ASP.NET?

后端 未结 6 1717
太阳男子
太阳男子 2020-11-27 12:27

I am creating cookies with following lines:

HttpCookie userid = new HttpCookie("userid", objUser.id.ToString());
userid.Expires.AddYears(1);
Respons         


        
6条回答
  •  一生所求
    2020-11-27 12:42

    FWIW be very careful with storing something like a userid in a cookie unencrypted. Doing this makes your site very prone to cookie poisoning where users can easily impersonate another user. If you are considering something like this I would highly recommend using the forms authentication cookie directly.

    bool persist = true;
    
    var cookie = FormsAuthentication.GetAuthCookie(loginUser.ContactId, persist);
    
    cookie.Expires = DateTime.Now.AddMonths(3);
    
    var ticket = FormsAuthentication.Decrypt(cookie.Value);
    
    var userData = "store any string values you want inside the ticket
                     extra than user id that will be encrypted"
    
    var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name,
         ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userData);
    
    cookie.Value = FormsAuthentication.Encrypt(newTicket);
    
    Response.Cookies.Add(cookie);
    

    Then you can read this at any time from an ASP.NET page by doing

    string userId = null;
    if (this.Context.User.Identity.IsAuthenticated) 
    {
        userId = this.Context.User.Identity.Name;
    }
    

提交回复
热议问题