1

I am creating a website using Asp.net core .

I wanted to know that is it a good and safe way to add admins of site to database using seed data ?

if not , how should i do this ?

2 Answers2

1

You can create an extension method for adding user into data base and call method in program.cs file or in configure method in startup class

According to Microsoft documentation better way is use this to using seed data

Program.cs

public static void Main(string[] args)
{
     var host = CreateWebHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        try
        {
            var context = services.GetRequiredService<DbContext>();
            DbInitializer.Initialize(context);
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred while seeding the database.");
        }
    }

    host.Run();
}

or Configure method way

public static void Initialize(this IApplicationBuilder app)
{
    using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        var dbContext = scope.ServiceProvider.GetServices<DbContext>();
        //insert data in database
    }
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Initialize();
}

and this link can be helpful for seeding admin user

Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41
0

I think farhad already explained the 'how' quite nicely. I'd like to add the following.

I work with a machine builder and we have to deal with the food and drug administration (an American legal entity that exercises execute power of safety and regulation around food and drugs for the American public) and their european counterpart. We're in the food category so its not as tight, legal wise, as pharmaceutical regulation, but still fairly tight. We also do what you're describing here.

We have certain roles, admin, operator, etc. and a 'default' account for each role gets created for each user. This is also nice for when, e.g. someone forgot to add an operator and you get a call that someone needs acces to your system for that specific role..

When we eventually ship our machine to the customer it becomes their property, and thus we change most roles and their accounts. We have a OEM role, which can basically do anything, for which only we have the login. This is basically a superuser, and is only used by us for maintenance. Its details are kept secret outside the company.

So - i think its pretty okay to seed admin data into your database, but it might be smart to enforce a 'first time use change the password' policy.

sommmen
  • 6,570
  • 2
  • 30
  • 51