![](/img/trans.png)
[英]Application Insights User ID from ASP.NET Core identity
[英]Remove registration from web application (EF, ASP.NET Identity, Azure) and register a user from DB
我想发布一个示例Web应用程序。 我不希望任何新用户注册,只是为了让一个用户能够登录进行测试。 我有一个正在运行的默认ASP.NET身份模块添加到具有LocalDb的应用程序。
现在我想把它放在Azure上。 我只是要删除“Register”控制器,但是DB将由Entity Framework自动创建。 由于密码存储在数据库中 - 我似乎无法从数据库中输入这个用户的密码。
我现在知道我太复杂了,我应该把这些凭证存储在代码中 - 因为保护这个应用程序没有很大的好处,但是因为我已经这样做了 - 也许有人会想到是否会是否可以从DB内部克服密码哈希创建用户名和密码?
您可以通过Entity Framework迁移轻松地为此用户帐户设定Seed(...)
- 特别是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());
}
}
}
}
Seed(...)
将在每次迁移结束时运行,因此我们只需检查我们的用户是否存在,如果不存在,则创建它们并分配已知密码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.