Home Seeding database with admin user--but he can't log in
Reply: 1

Seeding database with admin user--but he can't log in

Alex P
1#
Alex P Published in 2017-09-13 21:20:34Z

I am creating an MVC application and want to seed the database with a single admin user, who will have the ability to create other users. I'm currently doing as follows:

    ApplicationUser admin = new ApplicationUser
    {
        UserName = "whatever",
        Email = "whatever@mailinator.com",
        EmailConfirmed = true
    };

    string pwd = "password";

    var chkUser = await _userManager.CreateAsync(admin, pwd);
    if (chkUser.Succeeded)
    {
        await _userManager.AddToRoleAsync(admin, Constants.Roles.Administrator);
    }

This creates a user in the database, exactly as would be expected. But when I try to login with that user, I fail. Screenshot of the failure

This is especially puzzling to me, because I use almost the exact same code when users register themselves through the GUI, but there everything is working fine.

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
           a bunch of stuff regarding sending a confirmation email
            return RedirectToLocal(returnUrl);
        }
        AddErrors(result);
    }
     // If we got this far, something failed, redisplay form
    return View(model);'

In both methods, the variable _userManager is of type UserManager<ApplicationUser> and is supplied to my method through dependency injection.

Alex P
2#
Alex P Reply to 2017-09-13 21:27:12Z

When a user logs in, he is looked up by username. For the users that are created through the GUI, their email address and username are identical. But my "seed" user has a username that is different from his email address. So when he tries to login, the system tries to find a user whose username matches my seed user's email address--and fails.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.40178 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO