我有一个.NET Core 2.0 Web API。我正在使用Jwt身份验证。
每当应用程序到达此行时,都会抛出异常:
public async Task Seed()
{
var adminUserJ = await _userManager.FindByNameAsync("Ciwan");
var regularUser = await _userManager.FindByNameAsync("John");
if (adminUserJ == null)
{
if (!await _roleManager.RoleExistsAsync("Admin"))
{
var role = new IdentityRole("Admin");
role.Claims.Add(new IdentityRoleClaim<string> { ClaimType = "IsAdmin", ClaimValue = "True" });
await _roleManager.CreateAsync(role);
}
adminUserJ = new BbUser
{
UserName = "Ciwan",
Email = "ck83s9@gmail.com"
};
var userResult = await _userManager.CreateAsync(adminUserJ, "Welcome123");
var roleResult = await _userManager.AddToRoleAsync(adminUserJ, "Admin");
var claimResult = await _userManager.AddClaimAsync(adminUserJ, new Claim("Points", "10"));
if (!userResult.Succeeded || !roleResult.Succeeded || !claimResult.Succeeded)
{
throw new InvalidOperationException("Failed to build user and roles");
}
}
if (regularUser == null)
{
if (!await _roleManager.RoleExistsAsync("Regular"))
{
var role = new IdentityRole("Regular");
role.Claims.Add(new IdentityRoleClaim<string> { ClaimType = "IsRegular", ClaimValue = "True" });
await _roleManager.CreateAsync(role);
}
regularUser = new BbUser
{
UserName = "John",
Email = "j.watson@world.com"
};
var userResult = await _userManager.CreateAsync(regularUser, "BigWow321");
var roleResult = await _userManager.AddToRoleAsync(regularUser, "Regular");
var claimResult = await _userManager.AddClaimAsync(regularUser, new Claim("Points", "10"));
if (!userResult.Succeeded || !roleResult.Succeeded || !claimResult.Succeeded)
{
throw new InvalidOperationException("Failed to build user and roles");
}
}
_context.AddRange(GetListOfArtists(adminUserJ.Id, regularUser.Id));
await _context.SaveChangesAsync();
}
例外是:
System.InvalidOperationException :序列包含多个匹配元素
奇怪的是,之前没有发生这种情况,当我从1.1升级到.NET Core 2.0时,它开始发生。
数据库的种子方法如下:
AspNetUserClaims
我看不出有什么不对。我试着查看数据库中的[HttpPost("auth/token")]
public async Task<IActionResult> CreateToken([FromBody] CredentialsDto credentials)
{
try
{
var user = await _userManager.FindByNameAsync(credentials.Username);
if (user != null)
{
if (IsUserPasswordValid(credentials, user))
{
var claims = await GetClaimsAsync(user);
var token = CreateNewJwtToken(claims);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
});
}
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
return BadRequest("Failed to generate token!");
}
private async Task<IEnumerable<Claim>> GetClaimsAsync(BbUser user)
{
var userClaims = await _userManager.GetClaimsAsync(user);
return new[] {
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}.Union(userClaims);
}
表,但一切似乎都没问题。我有2个声明,每个用户一个。
当我尝试登录用户时会发生此错误,因此请求到达此处:
{{1}}