【问题标题】:Seed ASP.NET Core 1.1 database with a default super-user使用默认超级用户播种 ASP.NET Core 1.1 数据库
【发布时间】:2018-02-09 15:51:08
【问题描述】:

我正在使用 Identity 进行身份验证开始一个新的 ASP.NET Core 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
        }
    }

【问题讨论】:

    标签: c# entity-framework-core asp.net-core-1.1 asp.net-core-identity


    【解决方案1】:

    好的,这就是我如何实现它以添加管理员用户。我正在使用基于声明的授权。

    创建一个初始化器类:

    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>();
    

    最后,像这样更改 Configure 方法:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IDbInitializer dbInitializer)
    

    并在其中添加对 Initialize 方法的调用:

      dbInitializer.Initialize();
    

    DI 会处理剩下的事情。

    这是我作为参考的完整代码。它使用角色基础授权: https://gist.github.com/mombrea/9a49716841254ab1d2dabd49144ec092

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多