c# - 从 Web 应用程序(EF、ASP.NET Identity、Azure)中删除注册并从 DB 中注册用户

标签 c# asp.net entity-framework azure asp.net-identity

我想发布一个示例 Web 应用程序。我不希望注册任何新用户,只是希望有一个用户能够登录进行测试。我有一个正在运行的默认 ASP.NET Identity 模块添加到具有 LocalDb 的应用程序中。

现在我想把它放在 Azure 上。我只是要删除“注册” Controller ,但数据库将由 Entity Framework 自动创建。由于密码以散列形式存储在数据库中 - 我似乎无法从数据库中输入该单个用户的密码。

我现在知道我把这件事复杂化了太多,我应该将这些凭据存储在代码中 - 因为保护这个应用程序并没有太大的好处,但因为我已经这样做了 - 也许有人会有一个想法是否有一个选项可以从数据库中创建用户名和密码来克服密码哈希?

最佳答案

您可以通过 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, "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8dfee2e0e8f8fee8ffcde8e0ece4e1a3eee2e0" rel="noreferrer noopener nofollow">[email protected]</a>", "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());
            }
        }
    }
}

Seed(...) 将在每次迁移结束时运行,因此我们只需检查用户是否存在,如果不存在,则创建它们并分配已知密码。

关于c# - 从 Web 应用程序(EF、ASP.NET Identity、Azure)中删除注册并从 DB 中注册用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37309717/

相关文章:

c# - CE 上的抗锯齿 DrawLine

c# - ORA-01882 : timezone region not found in Entity Framework

c# - 一对一关系字段导致 razor 详细信息页面上出现 NullReferenceException( Entity Framework )

c# - XElement.ToString() 导致 System.OutOfMemoryException

c# - Visual Studio 调试很慢

java - 将 Long 转换为 DateTime 从 C# 日期到 Java 日期

javascript - 我向我的登录控件添加了 javascript 验证,尽管存在错误

asp.net - 我是否应该对映射表使用复合键,该复合键也用于外键?

c# - 带有 Google 的 ASP 网络文本框,如下拉搜索值

c# - 将其构建为一个语句?