我正在使用EF7为数据端编写一个简单的MVC6应用程序,并且在设置用户和声明时遇到了一些问题。具体来说,我有一个数据库种子例程来填充具有特定声明的特定用户(我)的数据库中的身份表。从startup.cs中调用此种子方法。
非常简单:
public static async Task CreateMasterUser( UserManager<ApplicationUser> userMgr, ILogger logger )
{
var user = await userMgr.FindByEmailAsync("my email");
if( user == null )
{
user = new ApplicationUser()
{
Email = "my email",
FirstName = "blah",
LastName = "blah",
UserName = "Blah",
};
IdentityResult result = await userMgr.CreateAsync(user, "mypw");
if( !result.Succeeded )
{
logger.LogCritical("Failed to create master user. Messages were: " + String.Join("; ", result.Errors.Select(x => x.Description)));
return;
}
}
await AddClaim(user, userMgr, "user.add", "allowed");
await AddClaim(user, userMgr, "user.delete", "allowed");
await AddClaim(user, userMgr, "user.edit.self", "allowed");
await AddClaim(user, userMgr, "user.edit.all", "allowed");
await AddClaim(user, userMgr, "user.confirm", "allowed");
await AddClaim(user, userMgr, "content.add", "allowed");
await AddClaim(user, userMgr, "content.view", "allowed");
await AddClaim(user, userMgr, "content.edit", "allowed");
await AddClaim(user, userMgr, "content.delete", "allowed");
}
private static async Task AddClaim( ApplicationUser user, UserManager<ApplicationUser> userMgr, string claim, string value )
{
if( user.Claims.SingleOrDefault(x => x.ClaimType == claim) == null )
await userMgr.AddClaimAsync(user, new Claim(claim, value));
}
但索赔部分存在问题:每次网站启动时,都会为我添加一组新的声明(即,正在为同一用户创建重复声明)。
当我单步执行代码时,user.Claims永远不会有任何条目,即使数据库(sql server)在相关用户的AspNetUserClaims中显示条目。
似乎FindEmailAsync没有从数据库中填充Claims集合。
我该如何实现?
答案 0 :(得分:1)
看一下UserManager的GetClaimsAsync方法。明确填写您的索赔集。
user.Claims = await userMgr.GetClaimsAsync(user);