2017-05-16 24 views
0

我需要在用戶登錄後更新web api中的用戶聲明。 但更新用戶聲明後,它仍然會返回以前的值。 波紋管代碼中使用的用戶登錄後,更新活躍用戶組。用戶聲明更新不受ASP.NET身份影響?

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

的問題是,權利要求書在認證過程中使用,並且所述認證令牌/餅乾的一部分。如果你想從當前用戶移除一個聲明,那麼你需要確保客戶端得到一個新的令牌/ cookie。

如果你正在用api運行例如持票人令牌,那麼你需要生成一個新的令牌並且從你的UpdateUserGroup()將該令牌返回給客戶端。然後,客戶端需要在下一次向api發出請求時使用新的令牌。

+0

如何在未實現的帳戶控制器中生成新令牌OAuthAuthorizationServerProvider – Wella

+0

@Wella您可以將OAuthAuthorizationServerOptions作爲靜態變量存儲在Startup.Auth.cs中,然後通過身份驗證選項初始化,然後從accountcontroller生成一個新的令牌。 –

+0

@Wella在此查看答案,以在控制器中生成新的令牌。 http://stackoverflow.com/questions/26969817/generate-token-in-controller –