0

I started my project as a .NET Core Web API project using Code-First EF (database managed via migration classes). I have my endpoints working but now need authentication.

I have scaffolded identity by following the instructions here. I made sure to scaffold using my existing DB context and then ran the migration code. The required tables for Identity were created on my SQL local database.

My next step is to create a default admin user using the .NET API. From several sources I found online, it looks like I can create the user via the UserManager (and RoleManager) class, something like this:

userManager.CreateAsync(user, ADMIN_PASSWORD).Result;

However, I want to call such code in the Startup.cs Configure function. How the userManager and roleManager.

It seems that the dependency injection is achieved when configuring the app with this line: app.UseAuthorization();

within the Configure class. That is how the classes are injected into the controller actions? Correct? But first, I need to create a default admin.

I do not want users to register. I just want this app to be used by admins.

How do I inject the usermanager?

Really, I just want a default admin created, so if doing it this way is wrong, that's fine, but where and how can I do it?

I don't know if this makes a difference, but the intention is to use JWT tokens with an Angular app.

TylerH
  • 20,799
  • 66
  • 75
  • 101
dhi
  • 43
  • 3

1 Answers1

0

Not sure if i understood correct. But creating Admin user (or any user for that matter) will be one time process. So i dont thik creating user code will be in startup.cs. You may have to develop other views to manager users. Or you can simply create users using SQL Script.

As far as getting instance of configured service, you can inject IServiceProvider in Configure method and then get instance of required service

public void Configure IServiceProvider sp)
{
        var um =  sp.GetRequiredService<IUserManager>();

}
LP13
  • 30,567
  • 53
  • 217
  • 400
  • Yes, it is a one time thing, but I was planning to add a condition to only add the admin if it does not already exist. I don't know of another way to do this (i.e. directly in the DB) since the way users are created is specific to the code used by .Net. Aside from GetRequiredSeruce, is there any way to inject this object? – dhi Jun 29 '20 at 22:50
  • if you cant do it using Sql script then you may have to create different application that has UI ( like MVC) and mange users that way. – LP13 Jun 30 '20 at 05:21