ASP.Net 在 Auth Cookie 中存储用户数据

标签 asp.net authentication forms-authentication membership

我想在 auth cookie 的用户数据部分存储一些数据,例如用户昵称和用户 ID(表主键)。我这样做的原因是在浏览器关闭时保留这些数据,而不需要用户重新登录。

编辑:哎呀!意识到我没有很好地解释自己。我并不是想根据用户的 cookie 重新验证用户的身份。用户已经通过 ASP.Net 的成员(member)系统进行身份验证 - 这部分没问题。我的问题是,例如,如果我想显示用户的昵称,我必须触发另一个 SQL 查询,然后将其存储在 session 中。我认为将此信息存储在 UserData 部分的 auth cookie(同样是由 ASP.Net 创建的)中是有意义的,该部分似乎是为此目的而创建的。

我不想使用个人资料,因为我有自己的包含个人资料数据的用户表,并且我需要一个轻量级的解决方案。

在 auth cookie 的用户数据部分对此数据进行编码的好方法是什么?我正在考虑连载,但这可能有点矫枉过正。我是否以错误的方式处理这个问题?

最佳答案

我在这里编写了有关如何执行此操作的深入教程:

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

这维护了加密和身份验证,并使用 json 将类序列化到 UserData 字段中。

编辑:

该博客已不存在,可以找到存档on the web archive here .

博客摘要:

获取现有的 cookie 和身份验证票

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

定义您的自定义数据(确保它可序列化为 json)

var userData = new YourUserClass(...);

使用您的数据和现有的身份验证票证设置创建新的身份验证票证

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

将您的自定义票证设置到 cookie 中并添加到响应

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

关于ASP.Net 在 Auth Cookie 中存储用户数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1070411/

相关文章:

javascript - MVC3,同一个页面View之间的切换

asp.net - jquery ajax post 转到 MVC 4 中的错误操作方法

asp.net - 错误 "dotnet : Could not find any project in ` C :\** ."when running "dotnet add package Microsoft. AspNetCore.Authentication.MicrosoftAccount”

ASP.NET Forms 身份验证需要启用匿名

c# - 如何在列表框中放入\n(换行)?

c# - 如何在 ASP.NET 中路由 "pretty"动态 URL(没有查询字符串)?

c# - SharePoint 2013 测试登录用户

c# - 对象引用,无法找到用户 ID

c# - 在 .net 中重置 IIS 后经过身份验证的用户

asp.net - 使用表单例份验证时获取 Windows 用户 ID