身份验证后存储 Id ASP net web 表单

Store Id after authentication ASP net web forms

我想在通过电子邮件和密码进行表单身份验证后保存用户 ID。我目前正在使用一个会话来这样做;

但是,会话和表单身份验证具有不同的超时时间,并且因为当一个用户登录时会话是服务器类型的变量,如果我在另一台计算机上使用不同的用户名登录,会话会简单地更改其值,即一个重大问题。

除了缓存还有什么其他的方法可以实现吗?

您可以将用户 ID 存储在扩展的身份验证 cookie 中。在授权例程中编写自定义 cookie 并将其添加到响应中:

var ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(60), false, userId.ToString()));
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)) { HttpOnly = true });

您可以为经过身份验证的请求解密该 cookie,并找出用户 ID:

HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];  
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
int iserId = int.Parse(authTicket.UserData);