使用管理员用户播种数据库-但他无法登录 [英] Seeding database with admin user--but he can't log in

查看:60
本文介绍了使用管理员用户播种数据库-但他无法登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个MVC应用程序,并希望使用一个管理员用户来播种数据库,该管理员将具有创建其他用户的能力.我目前正在执行以下操作:

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

这让我感到特别困惑,因为当用户通过GUI注册自己时,我使用几乎完全相同的代码,但是一切正常.

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);'

在这两种方法中,变量 _userManager 的类型均为 UserManager< ApplicationUser> ,并通过依赖项注入提供给我的方法.

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

推荐答案

用户登录时,将按用户名查找他.对于通过GUI创建的用户,其电子邮件地址和用户名相同.但是我的种子"用户的用户名不同于他的电子邮件地址.因此,当他尝试登录时,系统会尝试找到一个用户名与我的种子用户的电子邮件地址相匹配的用户,并且失败.

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.

这篇关于使用管理员用户播种数据库-但他无法登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆