I'm starting a new ASP.NET Core MVC project using Identity for authentication. I'd like to add a default super-user to the asp database, so it could add new users then, but i don't know how to do that.
First, i don't know if it is a good idea to use the same database for User's authentication/authorisation and for the rest of the application, or if i should use different databases.
Second, i need to know how to seed the "asp database" with a default super-user.
Following this solution from StackOverflow i know how to access the database, but i'd like to also be abble to get a "userManager" instance to add the super-user to the database using the manager in place of the context.
I have this code at the Startup class:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
Seed(app);
}
public void Seed(IApplicationBuilder app)
{
using (var context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>())
{
//... perform other seed operations
}
}
Ok, here is how i have implemented it to add an Admin user. I'm using claims based authorization.
Create a Initializer class:
And at the startup.cs, add this service at ConfigureService method:
And finally, change the Configure method like this:
and add in it the call to the Initialize method:
The DI will take care of the rest.
Here is the full code that i took as reference. It uses Role base authorization: https://gist.github.com/mombrea/9a49716841254ab1d2dabd49144ec092