用户声明更新在ASP.NET身份中不受影响?

时间:2017-05-16 05:08:55

标签: asp.net-web-api identity claims

我需要在用户登录后更新web api中的用户声明。 但在更新用户声明后,它仍将返回先前的值。 用户在用户登录后更新活动用户组的代码。

/// <summary>
/// The class AppUser
/// </summary>
public class AppUser : ClaimsPrincipal
{
    /// <summary>
    /// Initializes a new instance of the <see cref="AppUser"/> class.
    /// </summary>
    /// <param name="principal">The principal.</param>
    public AppUser(ClaimsPrincipal principal)
        : base(principal)
    {
    }

    /// <summary>
    /// Gets the name.
    /// </summary>
    /// <value>
    /// The name.
    /// </value>
    public string Name
    {
        get
        {
            return this.FindFirst(ClaimTypes.Name).Value;
        }
    }

    /// <summary>
    /// Gets the name of the user.
    /// </summary>
    /// <value>
    /// The name of the user.
    /// </value>
    public string UserName
    {
        get
        {
            return this.FindFirst("UserName").Value;
        }
    }

    /// <summary>
    /// Gets the active group.
    /// </summary>
    /// <value>
    /// The active group.
    /// </value>
    public string ActiveGroup
    {
        get
        {
            return ((ClaimsIdentity)this.Identity).FindFirst("ActiveGroup").Value;
        }
    }

    /// <summary>
    /// Gets the email.
    /// </summary>
    /// <value>
    /// The email.
    /// </value>
    public string Email
    {
        get
        {
            return this.FindFirst("Email").Value;
        }
    }
}


/// <summary>
/// The class BaseController
/// </summary>
public class BaseController : ApiController
{
    /// <summary>
    /// Gets the current user.
    /// </summary>
    /// <value>
    /// The current user.
    /// </value>
    public AppUser CurrentUser
    {
        get
        {
            return new AppUser(this.User as ClaimsPrincipal);
        }
    }
}



public class AccountController : BaseController
{

    [HttpPost]
    [Route("UpdateUserGroup")]
    public int UpdateUserGroup(string userGroup)
    {
        var user = User as ClaimsPrincipal;
        var identity = user.Identity as ClaimsIdentity;
        identity.RemoveClaim(identity.FindFirst("ActiveGroup"));
        identity.AddClaim(new Claim("ActiveGroup", this.GetRoleNameByPresenter(userGroup)));
        return 1;
    }
 }

1 个答案:

答案 0 :(得分:1)

问题是声明在身份验证过程中使用,并且是身份验证令牌/ Cookie的一部分。如果您要从当前用户中删除声明,则需要确保客户端获得新的令牌/ cookie。

如果您使用api运行例如持有人令牌,则需要生成新令牌并从UpdateUserGroup()将该令牌返回给客户端。然后,客户端在下次向api发出请求时需要使用新令牌。