我使用身份验证的身份开始了一个新的ASP.NET Core MVC项目。我想在ASP数据库中添加默认超级用户,因此它可以添加新用户,但我不知道该怎么做。
首先,我不知道将相同的数据库用于用户的身份验证/授权以及应用程序的其余部分是一个好主意,或者我是否应该使用不同的数据库。
第二,我需要知道如何用默认超级用户播种" ASP数据库"。
从Stackoverflow遵循此解决方案,我知道如何访问数据库,但是我也想使用Manager代替上下文来获取" Usermanager"实例,以将超级用户添加到数据库中。
我在启动类中有此代码:
// 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
}
}
好吧,这是我实现它以添加管理员用户的方式。我正在使用基于索赔的授权。
创建一个初始化程序类:
public interface IDbInitializer
{
void Initialize();
}
(...)
public class DbInitializer : IDbInitializer
{
private readonly ApplicationDbContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public DbInitializer(
ApplicationDbContext context,
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
{
_context = context;
_userManager = userManager;
_roleManager = roleManager;
}
//This example just creates an Administrator role and one Admin users
public async void Initialize()
{
//create database schema if none exists
_context.Database.EnsureCreated();
//Create the default Admin account
string password = "password";
ApplicationUser user = new ApplicationUser {
UserName = "Admin",
Email = "my@mail.com",
EmailConfirmed = true
};
user.Claims.Add(new IdentityUserClaim<string> { ClaimType = ClaimTypes.Role, ClaimValue = "Admin" });
var result = await _userManager.CreateAsync(user, password);
}
}
和在startup.cs上,在configureservice方法上添加此服务:
services.AddScoped<IDbInitializer, DbInitializer>();
最后,更改这样的配置方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IDbInitializer dbInitializer)
并将其添加到初始化方法中:
dbInitializer.Initialize();
DI将照顾其余的。
这是我作为参考的完整代码。它使用角色基础授权:https://gist.github.com/mombrea/9a49716841254ab1d2dabd491444ec092