在创建新用户时添加声明

时间:2016-09-19 16:32:16

标签: c# asp.net-core asp.net-identity asp.net-identity-3

我正在使用ASP.NET Core Identity创建一个新用户,如下所示:

new User {
  Email = "john@company.com",
  Name = "John"
}

await userManager.CreateAsync(user, "password");

我需要在创建用户时添加声明。我试过了:

new User {
  Email = "john@company.com",
  Name = "John",
  Claims = new List<Claim> { /* Claims to be added */ }  
}

但理赔财产是只读的。

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:36)

您可以使用UserManager<YourUser>.AddClaimAsync方法向用户添加声明

var user = new User {
  Email = "john@company.com",
  Name = "John"
}

await userManager.CreateAsync(user, "password");

await userManager.AddClaimAsync(user, new System.Security.Claims.Claim("your-claim", "your-value"));

或向用户Claims集合

添加声明
var user = new User {
  Email = "john@company.com",
  Name = "John"
}

user.Claims.Add(new IdentityUserClaim<string> 
{ 
    ClaimType="your-type", 
    ClaimValue="your-value" 
});

await userManager.CreateAsync(user);