I want to publish a sample web application. I don't want any new users to register, just to have a single user who will be able to login for testing purposes. I have a running default ASP.NET Identity module added to app having a LocalDb.
Now I want to put it on Azure. I was just going to remove the "Register" controller, but DB is going to be created automatically by Entity Framework. As passwords are stored hashed in the DB - there seems to be no way for me to enter this single users' password from within DB.
I know now that I complicated this far too much, I should have just stored these credentials in code - as there is not a great benefit from securing this application, but since I have already done this - maybe somebody would have an idea if there would be an option to create a username and password from within DB overcoming the password hash?
You can easily seed this user account via Entity Framework migrations - specifically the Seed(...) method.
With migrations enabled, you can create a Configuration class along the lines of the following:
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, "[email protected]", "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());
}
}
}
}
The Seed(...) will run at the end of every migration, so we simply check to see if our user exists, and if not, create them and assign the known password.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With