如何使用asp.net core 1.1在mogodb中使用基于角色的声明?

时间:2017-10-03 09:31:25

标签: mongodb asp.net-core asp.net-identity asp.net-core-1.0 asp.net-core-identity

我正在使用 Asp.net核心 Application.I想在我的应用程序中使用基于角色的声明,我尝试过以下代码,但它不起作用。它不在db中创建aspnetrolesclaim表。我做错了吗?

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            CreateRolesAndAdminUser(app);
        }

        private async Task CreateRolesAndAdminUser(IApplicationBuilder app)
        {
            var _roleManager = app.ApplicationServices.GetRequiredService<RoleManager<ApplicationRole>>();
            var roleExists = await _roleManager.RoleExistsAsync("Admin");

            if (!roleExists)
            {
                var role = new ApplicationRole()
                {
                    Name = RoleName.SuperUser,
                    NormalizedName = RoleName.SuperUser.ToUpper(),
                };
                await _roleManager.CreateAsync(role);
                await _roleManager.AddClaimAsync(role, new Claim("User","Create"));
                await _roleManager.AddClaimAsync(role, new Claim("User","Edit"));
                await _roleManager.AddClaimAsync(role, new Claim("User", "Delete"));
            }


            string adminUserEmail = "admin@adminstore.com";
            string adminPwd = "admin@123";

            var _userManager = app.ApplicationServices.GetRequiredService<UserManager<ApplicationUser>>();

            var checkAppUser = await _userManager.FindByEmailAsync(adminUserEmail);

            if (checkAppUser == null)
            {
                ApplicationUser newAppUser = new ApplicationUser
                {
                    Email = adminUserEmail,
                    UserName = adminUserEmail,
                    NormalizedEmail = adminUserEmail.ToUpper(),
                    NormalizedUserName = adminUserEmail.ToUpper(),
                };
                await _userManager.CreateAsync(newAppUser, adminPwd);
                await _userManager.AddToRoleAsync(newAppUser,"Admin");
            }
        }

0 个答案:

没有答案