【问题标题】:why does FindByNameAsync always return null?为什么 FindByNameAsync 总是返回 null?
【发布时间】:2020-03-21 16:58:28
【问题描述】:

尝试通过 post 请求验证令牌,当我通过用户名检查时,用户总是返回 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 = "test@test.com",
                    SecurityStamp = Guid.NewGuid().ToString(),
                    UserName = "testTest"

                };
                userManager.CreateAsync(user, "Password123");
                context.Users.Add(user);
                context.SaveChanges();
            }

        }
    }

在我为我的数据库播种后,我可以看到我在字段中创建的用户,它在那里的 defo,所以不明白这里似乎是什么问题!

【问题讨论】:

  • 即使您在该行之后主动等待几秒钟,用户是否仍为 null,可能使用调试器?
  • 是的,不管我等待多久,它总是为空

标签: c# authentication asp.net-core .net-core entity-framework-core


【解决方案1】:

首先要检查数据库,确认你的用户是否创建成功。您可以先检查几个问题:

  1. 对于userManager.FindByNameAsync,请确认您输入的是AndyCosStav,而不是电子邮件。

  2. CheckPasswordAsync 返回一个标志,指示给定密码是否对指定用户有效。

    public virtual System.Threading.Tasks.Task<bool> CheckPasswordAsync (TUser user, string password);
    

    第二个参数应该是密码,我注意到你正在检查用户名:

    if (user !=null && await _userManager.CheckPasswordAsync(user,model.UserName))
    
  3. Password123 可能与默认的 ASP.NET Core 身份密码不匹配 限制,您必须至少有一个非字母数字字符。

【讨论】:

    猜你喜欢
    • 2014-09-12
    • 2019-09-18
    • 2014-09-02
    • 2015-02-27
    • 2021-01-10
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多