使用默认超级用户种子ASP.NET Core 1.1数据库
问题描述:
我开始使用Identity进行身份验证的新ASP.NET Core MVC项目。 我想添加一个默认的超级用户到asp数据库,所以它可以添加新用户,但我不知道该怎么做。使用默认超级用户种子ASP.NET Core 1.1数据库
首先,我不知道这是否是使用相同的数据库用户认证/授权和应用程序的其余部分是一个好主意,或者我应该使用不同的数据库。
其次,我需要知道如何播种“ASP数据库”使用默认的超级用户。
在从*的this解决方案,我知道如何访问数据库,但我想也abble得到“的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 = "[email protected]",
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/9a49716841254ab1d2dabd49144ec092