从 Web 应用程序中移除注册功能 (EF、ASP.NET Identity、Azure),并从数据库中注册用户。

3
我想发布一个示例Web应用程序。我不希望有任何新用户注册,只需要一个单一的用户可以登录进行测试。我已经在应用程序中添加了正在运行的默认ASP.NET Identity模块,它使用LocalDb。
现在我想把它放到Azure上。我本来打算删除“注册”控制器,但是DB将由Entity Framework自动创建。由于密码以哈希形式存储在DB中,似乎没有办法从DB内部输入此单个用户的密码。
我现在知道我把这个问题复杂化了,我应该只是把这些凭据存储在代码中-因为保护此应用程序没有太大的好处,但既然我已经这样做了-也许有人会想到是否有一种选项可以从DB内部创建用户名和密码,克服密码哈希?

1
我不确定我是否正确理解了问题,但为什么不在 Web 应用程序启动时检查用户是否存在,如果不存在,则创建它呢? - Chief Wiggum
这听起来是个好主意! - Turo
1
如果您正在使用EF的Code First,则可以轻松地为用户提供种子数据。 - Brendan Green
1个回答

1
你可以通过Entity Framework迁移轻松地为该用户帐户提供种子数据 - 具体来说,是通过Seed(...)方法。
启用迁移后,您可以创建类似以下内容的Configuration类:
public sealed class Configuration : DbMigrationsConfiguration<YourEFContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        ContextKey = "YourEFContext";
    }

    /// <summary>
    /// This method will be called after migrating to the latest version.
    /// </summary>
    /// <param name="context"></param>
    protected override void Seed(YourEFContext context)
    {
        CreateUserIfNotExists(context, "someuser@email.com", "the_password");
    }

    /// <summary>
    /// Just call directly into ASP.Net Identity to check if the user exists
    /// If not, create them
    /// </summary>
    private static void CreateUserIfNotExists(YourEFContext context, string email, string password)
    {
        // Use your application user class here
        var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

        // We're using email for the username
        if ((um.FindByEmail(email)) == null)
        {
            var au = new ApplicationUser
            {
                UserName = email,
                Email = email
            };

            var res = um.Create(au);

            if (res.Succeeded)
            {
                um.AddPassword(au.Id, password);
            }
            else
            {
                Console.WriteLine("Failed to create user: {0}", res.Errors.FirstOrDefault());
            }
        }
    }
}
< p > Seed(...) 在每次迁移结束时运行,因此我们只需检查用户是否存在,如果不存在,则创建该用户并分配已知密码。


谢谢Brendan,我正在处理这个问题,我使用了这个场景或者非常相似的场景,但是Seed方法似乎不会被Identity默认调用。看起来我应该从Global.asax中设置种子?像Database.SetInitializer<ApplicationDbContext>(new DbInitializer()); }内部类DbInitializer : MigrateDatabaseToLatestVersion<ApplicationDbContext, Migrations.Configuration>{} - Turo
不会的,当你运行迁移时它会被执行。这可能是在包管理器控制台中运行update-database,或者如果你配置了自动迁移。从全局运行将在每次应用程序池回收时执行。 - Brendan Green

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接