我想从 ASP.NET Core 中的后端或 cli 创建超级管理员或系统管理员

问题描述 投票:0回答:2

我正在构建一个应用程序,其中注册页面仅可供管理员用户使用,因此我可以将注册页面提供给管理员用户。但我需要创建一个可以创建这些用户的管理员用户。我无法通过任何 Api 做到这一点。

问题

我正在使用基于 JWT 令牌的身份验证。在基于 JWT 令牌的身份验证中,需要一定的过程来通过 C# 代码创建用户。 有什么方法可以在不调用 API 的情况下反手创建用户吗?

        [HttpPost]  
        [Route("register")]  
        public async Task<IActionResult> Register(RegisterModel model)  
        {  
            var userExists = await userManager.FindByNameAsync(model.Username);  
            if (userExists != null)  
                return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User already exists!" });  
  
            ApplicationUser user = new ApplicationUser()  
            {  
                Email = model.Email,  
                SecurityStamp = Guid.NewGuid().ToString(),  
                UserName = model.Username  
            };  
            var result = await userManager.CreateAsync(user, model.Password);  
            if (!result.Succeeded)  
                return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User creation failed! Please check user details and try again." });  
  
            return Ok(new Response { Status = "Success", Message = "User created successfully!" });  
        }  
  
        [HttpPost]  
        [Route("register-admin")]  
        public async Task<IActionResult> RegisterAdmin(RegisterModel model)  
        {  
            var userExists = await userManager.FindByNameAsync(model.Username);  
            if (userExists != null)  
                return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User already exists!" });  
  
            ApplicationUser user = new ApplicationUser()  
            {  
                Email = model.Email,  
                SecurityStamp = Guid.NewGuid().ToString(),  
                UserName = model.Username  
            };  
            var result = await userManager.CreateAsync(user, model.Password);  
            if (!result.Succeeded)  
                return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User creation failed! Please check user details and try again." });  
  
            if (!await roleManager.RoleExistsAsync(UserRoles.Admin))  
                await roleManager.CreateAsync(new IdentityRole(UserRoles.Admin));  
            if (!await roleManager.RoleExistsAsync(UserRoles.User))  
                await roleManager.CreateAsync(new IdentityRole(UserRoles.User));  
  
            if (await roleManager.RoleExistsAsync(UserRoles.Admin))  
            {  
                await userManager.AddToRoleAsync(user, UserRoles.Admin);  
            }  
  
            return Ok(new Response { Status = "Success", Message = "User created successfully!" });  
        } 


        public void ConfigureServices(IServiceCollection services)
        {

            // Allow Cross for Centain Network

            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                builder =>
                                {
                                    builder.WithOrigins(Configuration["JWT:ValidAudience"]);
                                });
            });


            services.AddControllers();

            // For Entity Framework  
            services.AddDbContext<DentalDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
  
            // For Identity  
            services.AddIdentity<ApplicationUser, IdentityRole>(options => 
            {
                options.Password.RequiredLength = 6;
                options.Password.RequireLowercase = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireDigit = false;
            })  
            .AddEntityFrameworkStores<DentalDbContext>()  
            .AddDefaultTokenProviders();  


              
            // Adding Authentication  
            services.AddAuthentication(options =>  
            {  
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;  
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;  
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;  
            })  
  
            // Adding Jwt Bearer  
            .AddJwtBearer(options =>  
            {  
                options.SaveToken = true;  
                options.RequireHttpsMetadata = false;  
                options.TokenValidationParameters = new TokenValidationParameters()  
                {  
                    ValidateIssuer = true,  
                    ValidateAudience = true,  
                    ValidAudience = Configuration["JWT:ValidAudience"],  
                    ValidIssuer = Configuration["JWT:ValidIssuer"],  
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))  
                };  
            });  

        }


 








 
c# asp.net-core authentication oauth
2个回答
1
投票

是的,如果您使用 Microsoft 的身份。这是有出路的。 在程序.cs中

        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();

            try
            {
                using var scope = host.Services.CreateScope();
                var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
                var userManager = scope.ServiceProvider.GetRequiredService<UserManager<IdentityUser>>();

                context.Database.EnsureCreated();

                if (!context.Users.Any())
                {
                    var superAdminUser= new IdentityUser
                    {
                        UserName = "SuperAdmin"
                    };

                    userManager.CreateAsync(superAdminUser, "SuperAdminPassword").GetAwaiter().GetResult();

                    //Roles contains user, user contains claims
                    var adminClaim = new Claim("Role", "SuperAdminUser");

                    userManager.AddClaimAsync(SuperAdminUser, adminClaim).GetAwaiter().GetResult();
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            host.Run();
        }

在启动使用授权中。

 services.AddAuthorization(options =>
 {
     options.AddPolicy("SuperAdmin", policy => policy.RequireClaim("Role", "SuperAdmin"));
 });

在控制器中专门为超级管理员角色添加授权

[Authorize(Policy = "SuperAdmin ")]
 public class SecretController : Controller
 {}

0
投票

在您的 Auth DBContext 中使用此代码,然后运行迁移命令

 var user = new IdentityUser { 
        UserName = " "
       };

      //set user password
      PasswordHasher<AppUser> ph = new PasswordHasher<IdentityUser>();
      user.passwordHash = ph.HashPassword(user, "the password");

      //seed user
      builder.Entity<IdentityUser>().HasData(user);
        
      //set user role to admin
      builder.Entity<IdentityUserRole<string>>().HasData(new 
       IdentityUserRole<string> { 
       RoleId = "your role ID", 
       UserId = "The User ID" 
      });
© www.soinside.com 2019 - 2024. All rights reserved.