续订FormsAuthenticationTicket UserData

时间:2014-02-11 07:54:04

标签: c# cookies forms-authentication

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

我是否可以检索此参数,而无需用户再次登录?

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

Cookie套装。 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;
}

1 个答案:

答案 0 :(得分:1)

您使用的是网络表单还是MVC?

看起来您正确设置了HttpContext.Current.User。问题可能是您的控制器/视图默认仍然认为其IPrincipal而不是您的自定义主体,因此您无法访问您设置的新数据。

您可以将其投射,或将其设置在如下的基本控制器中。

// 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; }
    }
}