我正在启动一个新的ASP.NET核心MVC项目,使用身份进行身份验证。我想添加一个默认的超级用户到asp数据库,这样它就可以添加新用户,但我不知道怎么做。
首先,我不知道使用相同的数据库进行用户身份验证/授权和应用程序的其余部分是不是一个好主意,或者我是否应该使用不同的数据库。
其次,我需要知道如何给"asp数据库“设置一个默认的超级用户。
遵循StackOverflow的this解决方案,我知道如何访问数据库,但我也希望能够获得一个"userManager“实例,以便使用管理器代替上下文将超级用户添加到数据库中。
我在Startup课程上有这样的代码:
// 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
}
}发布于 2017-09-01 18:52:25
好的,下面是我如何实现它来添加一个Admin用户。我使用的是基于声明的授权。
创建一个初始化程序类:
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)并在其中添加对Initialize方法的调用:
dbInitializer.Initialize();DI会处理剩下的事情。
下面是我参考的完整代码。它使用基于角色的授权:https://gist.github.com/mombrea/9a49716841254ab1d2dabd49144ec092
https://stackoverflow.com/questions/45985698
复制相似问题