ASP.Net Store User Data in Auth Cookie

限于喜欢 提交于 2019-11-28 18:40:56
DanH

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);

Apparently I was on the right track: http://www.asp.net/learn/security/tutorial-03-vb.aspx (Step 4: Step 4: Storing Additional User Data in the Ticket)

Yes. If you are storing the User ID and Login in the cookie what's stopping someone from changing their cookies to anyone's User ID and Login?

You need to set up an auth ticket system. Basically it's a cookie value that gets checked when no session exists. If a value is present you run that against a ticket table which should contain their User ID. If you find the ticket, give them a session and a new ticket.

If you've already got a user table with profile information in it, why don't you hook into it with a custom profile provider.

If you want another example of how to implement something like this, you could take a look at the SQL Table Profile Provider

Maybe you could just create another cookie... I personally wouldn't mess with the auth cookie.

Storing extra user data in the cookie means a larger cookie that is sent back and forth from the client with every request.

A better approach to avoid the extra database hits you are worried about is to cache that data in memory after the user logs in.

ASP.NET has a per request cache HttpContext.Current.Items and a app domain cache HttpContext.Current.Cache, I think you are looking for HttpContext.Current.Cache in this instance.

Alternatively if you need caching across web servers (load balanced web servers) you can look into 3rd party key value stores like like memcached, redis, velocity, ncache etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!