why does FindByNameAsync always return null?

.net-core asp.net-core authentication c# entity-framework-core

Question

trying to authenticate a token through a post request, user always returns null when i check via the username.

    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();
    }

wondering if the problem is coming from how i seeded my database with this dummy data class?

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 = "andy@stav.com",
                    SecurityStamp = Guid.NewGuid().ToString(),
                    UserName = "AndyCosStav"

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

        }
    }

After I seed my database i can see my the user created in the fields, its defo there, so not understanding what seems to be the issue here!

1
0
3/23/2020 6:59:31 AM

Popular Answer

The first thing is to check the database to confirm whether your user is successfully created . There are several issues you can check firstly :

  1. For userManager.FindByNameAsync confirm that you are typing the AndyCosStav , not the email .

  2. The CheckPasswordAsync returns a flag indicating whether the given password is valid for the specified user.

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

    The second parameter should be the password , i notice you are checking with username :

    if (user !=null && await _userManager.CheckPasswordAsync(user,model.UserName))
    
  3. Password123 may not match the defalut ASP.NET Core identity password restrict , you must have at least one non alphanumeric character.

0
3/23/2020 7:24:40 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow