gpt4 book ai didi

c# - 更新 FormsAuthenticationTicket 用户数据

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:56 30 4
gpt4 key购买 nike

在我的登录页面上,FormsAuthenticationTicket 被设置为带有一些自定义用户数据的持久性 cookie。现在我需要更改此自定义用户数据,因此它包含一个多参数。当以前登录的用户下次访问该站点时,我在 Application_PostAuthenticateRequest 中反序列化此自定义用户数据,但现在我不会包含新添加的参数。

我可以检索这个参数,而不需要用户再次登录吗?

如果没有,如何告诉持久性 cookie 它需要“更新”?

cookies 集。 userId 是一个新参数:

CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
serializeModel.FirstName = model.UserName;
serializeModel.userId = model.userId;

JavaScriptSerializer serializer = new JavaScriptSerializer();

string userData = serializer.Serialize(serializeModel);

FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
model.UserName,
DateTime.Now,
DateTime.Now.AddYears(5),
model.RememberMe,
userData);

string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

faCookie.Expires = authTicket.Expiration;
Response.Cookies.Add(faCookie);

return RedirectToAction("Index", "Home");

Cookie 检索。 Userid 是新参数,对于以前登录的用户是null:

HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

JavaScriptSerializer serializer = new JavaScriptSerializer();

CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);

CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
newUser.FirstName = serializeModel.FirstName;
newUser.userId = serializeModel.userId;

HttpContext.Current.User = newUser;
}

最佳答案

您使用的是 Web 表单还是 MVC?

看起来您的 HttpContext.Current.User 设置正确。问题可能是默认情况下,您的 Controller / View 仍然认为它的 IPrincipal 而不是您的自定义委托(delegate)人,因此您无法访问您设置的新数据。

您可以转换它,或将其设置在如下所示的基本 Controller 中。

// in some controller action
var firstName = ((CustomPrincipal)User).FirstName


[Authorize]
public class BaseController : Controller
{
protected virtual new CustomPrincipal User
{
get { return HttpContext.User as CustomPrincipal; }
}
}

关于c# - 更新 FormsAuthenticationTicket 用户数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21696092/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com