【IdentityServer4】配置数据库

参考:【老张的哲学】Ids4实战

  • 自定义用户类(方便后续拓展)

     public class ApplicationUser : IdentityUser
     {
         public string Salt { get; set; } = GetRandomSalt(5, 5, 1, 1, 1);
    
         /// <summary>
         /// 获取加密的SHA256字符串
         /// </summary>
         /// <param name="password">明文</param>
         /// <returns>密文</returns>
         internal string GetEncryptPass(string password)
         {
             // 加盐拼接一下,再SHA256
             var buffer = Encoding.UTF8.GetBytes(UserName + password + Salt);
             var hash = SHA256.Create().ComputeHash(buffer);
             return string.Join("", hash.Select(x => x.ToString("x2")));
         }
    
         /// <summary>
         /// 检查密码明文是否通过(根据密文计算)
         /// </summary>
         internal bool ValidatePass(string password)
         {
             return PasswordHash == GetEncryptPass(password);
         }
    
         /// <summary>
         /// 随便搞一些大小写字符和符号
         /// </summary>
         private static string GetRandomSalt(int a, int b, int c, int d, int e)
         {
             var seed = int.Parse(DateTime.Now.Ticks.ToString().Substring(16));
             Random random = new Random(seed);
    
             List<int> res = new List<int>();
    
             for (int i = 0; i < a; i++)
             {
                 res.Add(random.Next('A', 'Z'));
             }
             for (int i = 0; i < b; i++)
             {
                 res.Add(random.Next('a', 'z'));
             }
             for (int i = 0; i < c; i++)
             {
                 res.Add(random.Next(':', '?'));
             }
             for (int i = 0; i < d; i++)
             {
                 res.Add(random.Next('[', '_'));
             }
             for (int i = 0; i < e; i++)
             {
                 res.Add(random.Next('!', '/'));
             }
    
             return new string(res.Select(x => (char)x).ToArray());
         }
     }
    
  • 定义用户 DBContext

     /// <summary>
     /// 为ApplicationUser定义自己的DBContext
     /// </summary>
     public class ApplicationDbContext:IdentityDbContext<ApplicationUser>
     {
         public DbSet<ApplicationUser> ApplicationUsers { get; set; }
         public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
         {
    
         }
     }
    
  • Startup.cs/ConfigureService 的一些配置

    
         public void ConfigureServices(IServiceCollection services)
         {
             services.AddControllersWithViews();
    
             #region 注册一些服务
             services.AddTransient<IUserRepository, UserRepository>();
             services.AddTransient<IApplicationUserService, ApplicationUserService>();
             services.AddTransient<IResourceOwnerPasswordValidator, PerryResourceOwnerPasswordValidator>();
             services.AddTransient<IProfileService, PerryProfileService>();
             services.AddAutoMapper(GetType().Assembly);
             #endregion
    
             var connId4Config = Configuration.GetConnectionString("ID4Configuration");
             var connId4User = Configuration.GetConnectionString("ID4User");
             var connId4Grant = Configuration.GetConnectionString("Id4PersistedGrant");
    
             #region 注册Identity用户
             // 数据库配置系统应用用户数据上下文
             services.AddDbContext<ApplicationDbContext>(builder =>
                 builder.UseMySql(connId4User,
                     new MySqlServerVersion(new System.Version(5, 7, 32)),
                     sqlOption =>
                     {
                         sqlOption.MigrationsAssembly(GetType().Assembly.FullName);
                     }));
    
             // 启用 Identity 服务 添加指定的用户和角色类型的默认标识系统配置
             services.AddIdentity<ApplicationUser, IdentityRole>()
                 .AddEntityFrameworkStores<ApplicationDbContext>()
                 .AddDefaultTokenProviders();
             #endregion
    
             var builder = services.AddIdentityServer(options =>
             {
                 options.Events.RaiseErrorEvents = true;
                 options.Events.RaiseInformationEvents = true;
                 options.Events.RaiseFailureEvents = true;
                 options.Events.RaiseSuccessEvents = true;
    
                 // see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
                 options.EmitStaticAudienceClaim = true;
             })
                 // 绑定用户类型
                 .AddAspNetIdentity<ApplicationUser>()
    
                 // 添加配置数据(客户端 和 资源)
                 .AddConfigurationStore(options =>
                 {
                     options.ConfigureDbContext = builder => builder.UseMySql(connId4Config,
                         new MySqlServerVersion(new System.Version(5, 7, 32)), sqlOption =>
                         {
                             sqlOption.MigrationsAssembly(GetType().Assembly.FullName);
                         });
                 })
                 // 添加操作数据 (codes, tokens, consents)
                 .AddOperationalStore(options =>
                 {
                     options.ConfigureDbContext = builder => builder.UseMySql(connId4Grant,
                         new MySqlServerVersion(new System.Version(5, 7, 32)), sqlOption =>
                         {
                             sqlOption.MigrationsAssembly(GetType().Assembly.FullName);
                         });
    
                     options.EnableTokenCleanup = true;
                 })
                 .AddResourceOwnerValidator<PerryResourceOwnerPasswordValidator>()
                 .AddProfileService<PerryProfileService>();
    
             // not recommended for production - you need to store your key material somewhere secure
             builder.AddDeveloperSigningCredential();
    
             services.AddAuthentication();
             //.AddGoogle(options =>
             //{
             //    options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
    
             //    // register your IdentityServer with Google at https://console.developers.google.com
             //    // enable the Google+ API
             //    // set the redirect URI to https://localhost:5001/signin-google
             //    options.ClientId = "copy client ID from Google here";
             //    options.ClientSecret = "copy client secret from Google here";
             //});
         }
    
    
  • 迁移数据库

    # 操作
    dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o ./Migrations/PersistedGrantDb
    dotnet ef database update -c PersistedGrantDbContext
    
    # 配置
    dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o ./Migrations/ConfigurationDb
    dotnet ef database update -c ConfigurationDbContext
    
    # 用户
    dotnet ef migrations add AppDbMigration -c ApplicationDbContext -o ./Migrations/ApplicationUser
    dotnet ef database update -c ApplicationDbContext
    
posted @ 2021-09-25 15:32  wosperry  阅读(274)  评论(0编辑  收藏  举报