ASP.Net Store User Data in Auth Cookie

后端 未结 6 578
情歌与酒
情歌与酒 2020-12-13 19:31

I want to store some data like the user nickname and user ID (table primary key) in the user data section of the auth cookie. The reason I\'m doing this is to retain this da

6条回答
  •  猫巷女王i
    2020-12-13 19:39

    I've written an in depth tutorial on how to do this here:

    http://www.danharman.net/2011/07/07/storing-custom-data-in-forms-authentication-tickets/

    This maintains the encryption and authentication, and uses json to serialize a class into the UserData field.

    Edit:

    The blog no longer exists, an archive can be found on the web archive here.

    Summary from blog:

    Get the existing cookie and auth ticket

    HttpResponse response = HttpContext.Current.Response;
    bool rememberMe = true;
    var cookie = FormsAuthentication.GetAuthCookie(name, rememberMe);
    var ticket = FormsAuthentication.Decrypt(cookie.Value);
    

    Define your custom data (make sure this is serializable to json)

    var userData = new YourUserClass(...);
    

    Create a new auth ticket with your data, and existing auth ticket settings

    var newTicket = new FormsAuthenticationTicket(ticket.Version, 
        ticket.Name, 
        ticket.IssueDate, 
        ticket.Expiration, 
        ticket.IsPersistent, 
        userData.ToJson(), //This is where you'd set your user data
        ticket.CookiePath);
    var encTicket = FormsAuthentication.Encrypt(newTicket);
    

    Set your customized ticket into cookie and add to response

    cookie.Value = encTicket;
    response.Cookies.Add(cookie);
    

提交回复
热议问题