繁体   English   中英

mvc3更改身份验证值

[英]mvc3 change authentication value

用户登录系统后,我已经在User.Identity.Name存储了身份验证信息。 使用这种方法

FormsAuthentication.SetAuthCookie(Id + " | " + Name + " | " + Language + " | " + Culture + " | " + Email + " | " + Role+ " | " + TimeOffset+ " | " + Rights, RememberMe);

现在我想在用户更改某些配置设置(例如Language时更改User.Identity.Name内部的某些值

但是在调用FormsAuthentication.SetAuthCookie()User.Identity.Name内部的值不再更改

string identity = HttpContext.Current.User.Identity.Name; // modify current value
FormsAuthentication.SetAuthCookie(identity, false); // assign new value

如何更改该值?

SetAuthCookie使用更新后的值更新包含FormsAuth票证的cookie,但不会设置当前上下文的User 您可以通过创建新的IPrincipalIIdentity来更改当前上下文的用户。 就像获取当前的HttpContext并设置User属性一样简单。

通常,您应该在PostAuthenticateRequest事件中的IHttpModule或Global.asax.cs中执行此操作,因为此时FormsAuth将已经对用户的票证进行了身份验证并设置了身份。 在此事件之后,您创建的新IPrincipal将在请求的其余部分中可供应用程序使用。

protected void Application_PostAuthenticateRequest(object sender, EventArgs args)
{
    var application = (HttpApplication)sender;
    var context = application.Context;

    if (context.User != null || !context.User.Identity.IsAuthenticated) return; // user not authenticated, so you don't need to do anything else

    // Here, you'd process the existing context.User.Identity.Name and split out the values you need. that part is up to you. in my example here, I'll just show you creating a new principal
    var oldUserName = context.User.Identity.Name;
    context.User = new GenericPrincipal(new GenericIdentity(oldUserName, "Forms"), new string[0]); 
}

顺便说一句,我不建议在标识名称中打包值,而建议在票证的UserData属性中打包。 在这种情况下,您可以检查context.User.Identity是否为FormsIdentity并访问Ticket.UserData

protected void Application_PostAuthenticateRequest(object sender, EventArgs args)
{
    var application = (HttpApplication)sender;
    var context = application.Context;

    if (context.User != null || !context.User.Identity.IsAuthenticated) return; // user not authenticated, so you don't need to do anything else

    var formsIdentity = context.User.Identity as FormsIdentity;

    if (formsIdentity == null) return; // not a forms identity, so we can't do any further processing

    var ticket = formsIdentity.Ticket;

    // now you can access ticket.UserData
    // to add your own values to UserData, you'll have to create the ticket manually when you first log the user in

    var values = ticket.UserData.Split('|');

    // etc.
    // I'll pretend the second element values is a comma-delimited list of roles for the user, just to illustrate my point
    var roles = values[1].Split(',');


    context.User = new GenericPrincipal(new GenericIdentity(ticket.Name, "Forms"), roles); 
}

是有关在UserData中使用自定义值创建FormsAuth票证的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM