gpt4 book ai didi

c# - FromsAuthenticationTicket.UserData 始终为空,身份验证 cookie 不保留值

转载 作者:行者123 更新时间:2023-11-30 23:11:37 24 4
gpt4 key购买 nike

我在登录(用户名,密码)中有以下代码

if (hasher.Compare(password, person.Hash))
{
FormsAuthentication.SetAuthCookie(userId, true);
OpenAccount(person);

var principle = new GenericPrincipal( new GenericIdentity($"{person.FirstName} {person.LastName}"), new string[] {"All"});
var data = Konstants.Serialize(principle);
var ticket = new FormsAuthenticationTicket(1, principle.Identity.Name, DateTime.Now, DateTime.Now.AddMinutes(30), true, data);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);


FormsAuthentication.SetAuthCookie(principle.Identity.Name, false);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.SetCookie(cookie);
Response.RedirectToRoute("Default");
}

然后在 Global.asax 中我有以下代码:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
try
{
if (authCookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
if (!string.IsNullOrEmpty(ticket.UserData))
{
var principle = Konstants.Deserialize<GenericPrincipal>(ticket.UserData);
HttpContext.Current.User = principle;
}
}
}
catch
{


}
}

但在 AutheticateRequest 中,ticket.UserData 始终为空。事实上,我得到的 cookie 值是身份验证之前的值,而不是我存储的值。我在这里做错了什么。

更新:序列化和反序列化代码如下:

   public static string Serialize<T>(T obj)
{
var ret = string.Empty;
using(var ms = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(ms, obj);
ret= Convert.ToBase64String(ms.GetBuffer());
}
return ret;
}

public static T Deserialize<T>(string text)
{
var obj = default(T);
var data = Convert.FromBase64String(text);
using(var ms = new MemoryStream(data, false))
{
var bf = new BinaryFormatter();
obj = (T)bf.Deserialize(ms);
}
return obj;
}

最佳答案

您在第一个代码块中调用了两次 SetAuthCookie,但如果您要创建自定义票证,则两者都不需要。我认为这应该可以解决问题:

OpenAccount(person);

var principle = new GenericPrincipal( new GenericIdentity($"{person.FirstName} {person.LastName}"), new string[] {"All"});
var data = Konstants.Serialize(principle);
var ticket = new FormsAuthenticationTicket(1, principle.Identity.Name, DateTime.Now, DateTime.Now.AddMinutes(30), true, data);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.SetCookie(cookie);
Response.RedirectToRoute("Default");

编辑:我刚刚还注意到您没有将序列化数据传递到新票证的 userData 字段中,这是故意的吗?

关于c# - FromsAuthenticationTicket.UserData 始终为空,身份验证 cookie 不保留值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44589224/

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