试图通过发布请求来验证令牌,当我通过用户名进行检查时,用户始终返回null。
public async Task<IActionResult> Login([FromBody] LoginModel model)
{
var user = await _userManager.FindByNameAsync(model.UserName); // user always equals null here
if (user !=null && await _userManager.CheckPasswordAsync(user,model.UserName))
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MySuperSecureKey"));
var token = new JwtSecurityToken(
issuer: "http://blah.com",
audience: "http://blah.com",
expires: DateTime.UtcNow.AddHours(1),
claims: claims,
signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256)
);
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
});
}
return Unauthorized();
}
想知道问题是否出在我如何用此虚拟数据类为数据库播种?
public class DummyData
{
public static void Initialize(IApplicationBuilder app, IServiceProvider serviceProvider)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<HealthContext>();
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
context.Database.EnsureCreated();
//context.Database.Migrate();
// Look for any ailments
if (context.Ailments != null && context.Ailments.Any())
return; // DB has already been seeded
var ailments = GetAilments().ToArray();
context.Ailments.AddRange(ailments);
context.SaveChanges();
var medications = GetMedications().ToArray();
context.Medications.AddRange(medications);
context.SaveChanges();
var patients = GetPatients(context).ToArray();
context.Patients.AddRange(patients);
context.SaveChanges();
if (!context.Users.Any())
{
ApplicationUser user = new ApplicationUser()
{
Email = "[email protected]",
SecurityStamp = Guid.NewGuid().ToString(),
UserName = "AndyCosStav"
};
userManager.CreateAsync(user, "Password123");
context.Users.Add(user);
context.SaveChanges();
}
}
}
在我为数据库添加种子之后,我可以看到我在该字段中创建的用户,它的配置在那里,所以不了解这里似乎是什么问题!
[第一件事是检查数据库以确认您的用户是否成功创建。您首先要检查几个问题:
对于userManager.FindByNameAsync
,请确认您输入的是AndyCosStav
,而不是电子邮件。
CheckPasswordAsync
返回一个标志,指示给定的密码对于指定用户是否有效。
public virtual System.Threading.Tasks.Task<bool> CheckPasswordAsync (TUser user, string password);
第二个参数应该是密码,我注意到您正在使用用户名:
if (user !=null && await _userManager.CheckPasswordAsync(user,model.UserName))
Password123
可能与默认的ASP.NET Core身份密码不匹配限制,您必须至少包含一个非字母数字字符。