尽可能避免使用会话,如果你可以在没有看见的情况下逃脱,它会使多服务器部署变得更容易一些。可能,姓名和电子邮件很容易成为 cookie 的候选者。伪造 cookie 很容易,因此根据您的安全需求,用户 ID 可能不是一个好主意。
表单身份验证 cookie 已加密,您可以向这些 cookie 添加额外数据(请参阅下面的详细信息)。它可能是可破解的,但不像简单的 cookie 那样容易。
这是我过去使用的代码,稍作修改以删除一些项目特定的细节。在登录控件的 LoggedIn 事件中调用它。
void AddUserIDToAuthCookie(string userID)
{
//There is no way to directly set the userdata portion of a FormAuthenticationTicket
//without re-writing the login portion of the Login control
//
//I find it easier to pull the cookie that the Login control inserted out
//and create a new cookie with the userdata set
HttpCookie authCookie = Response.Cookies[AUTH_COOKIE];
if(authCookie == null)
{
return;
}
Response.Cookies.Remove(AUTH_COOKIE);
FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(authCookie.Value);
var newTicket =
new FormsAuthenticationTicket(oldTicket.Version, oldTicket.Name, oldTicket.IssueDate, oldTicket.Expiration,
oldTicket.IsPersistent, userID, oldTicket.CookiePath);
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Add(authCookie);
}
仅供参考,我从一个旧项目中复制了它并在此处对其进行了编辑以删除一些项目特定的位,因此它可能无法编译,但它会非常接近。
要在您的网页中获取 ID...
FormsAuthenticationTicket ticket = ((FormsIdentity) Page.User.Identity).Ticket;
string id = ticket.UserData;
我使用这种机制来存储不属于 aspnetdb 用户数据的 id。如果您的所有身份数据都由 aspnetdb 处理,您可能只需要访问 Page.User.Identity 对象。