MVC 5 - 给用户添加声明

9

我正在开发一个MVC 5互联网应用程序,并使用Identity 2.1。

在用户登录后,如何向其添加 claim(声明),并且我知道 username(用户名)?

以下是我的代码:

public void AddClaimToUser(string userName, string type, string value )
{
    var AuthenticationManager = HttpContext.Current.GetOwinContext().Authentication;
    var Identity = new ClaimsIdentity(userName);
    Identity.AddClaim(new Claim(type, value));
    AuthenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(Identity), new AuthenticationProperties { IsPersistent = true });
}

不过,在我调用这个方法后,检查用户的声明时,新增的claim并没有列出。

以下是我在控制器中使用的代码来获取声明:

var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;

提前感谢您。

2个回答

3

首先,您需要在IdentityModels.cs类下创建一个添加声明的方法。代码如下,以下代码为CompanyId创建了一个声明。

public class ApplicationUser : IdentityUser
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public bool IsActive { get; set; }
  public int? CompanyId { get; set; }


public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{

  var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

  userIdentity.AddClaim(new Claim("CompanyId", (this.CompanyId + "" ?? "0")));

  return userIdentity;
}}

在编写了上述代码后,您需要在IdentityConfig.cs中再编写一个方法。
public static class IdentityExtensions{
public static int CompanyId(this IIdentity identity)
{
 return Convert.ToInt32(((ClaimsIdentity)identity).FindFirst("CompanyId").Value);
}}

在此之后,您只需在任何控制器中键入以下内容即可获取您创建的声明。
 int companyId = User.Identity.CompanyId();

0

仅提供AuthenticationResponseGrant是不足以向已登录用户添加声明的。您需要获取身份,添加新声明(您已经这样做了),然后注销用户并重新登录。我在this answer中基本上就是这样做的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接