初始化数据库

SeedData

SeedData 中的代码用于在数据库初始化两个 ApplicationUser。

在 Program 的 Main 方法中进行调用:

  1. public static void Main(string[] args)
  2. {
  3. var seed = args.Any(x => x == "/seed");
  4. if (seed) args = args.Except(new[] { "/seed" }).ToArray();
  5. var host = BuildWebHost(args);
  6. if (seed)
  7. {
  8. SeedData.EnsureSeedData(host.Services);
  9. return;
  10. }
  11. host.Run();
  12. }

dotnet run /seed
Full Stack 04 - 图1

SELECT * FROM archdb_dev.public.”AspNetUsers”;
查看生成的数据:
Full Stack 04 - 图2

还有 Claims
Full Stack 04 - 图3

InitializeDatabase

在 Startup.cs 中添加 InitializeDatabase 方法,并在 Configure 中调用:

  1. public void Configure(IApplicationBuilder app)
  2. {
  3. InitializeDatabase(app);
  4. if (Environment.IsDevelopment())
  5. ...
  6. }
  7. private void InitializeDatabase(IApplicationBuilder app)
  8. {
  9. // Using a services scope
  10. using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
  11. {
  12. // Create PersistedGrant Database (we're using a single db here)
  13. var persistedGrantDbContext = serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>();
  14. persistedGrantDbContext.Database.Migrate();
  15. // Create IdentityServer4 Configuration Database
  16. var configDbContext = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
  17. configDbContext.Database.Migrate();
  18. // Generate records corresponding to the clients
  19. if (!configDbContext.Clients.Any())
  20. {
  21. foreach (var client in Config.GetClients())
  22. {
  23. configDbContext.Clients.Add(client.ToEntity());
  24. }
  25. configDbContext.SaveChanges();
  26. }
  27. // Generate records corresponding to the identity resources
  28. if (!configDbContext.IdentityResources.Any())
  29. {
  30. foreach (var res in Config.GetIdentityResources())
  31. {
  32. configDbContext.IdentityResources.Add(res.ToEntity());
  33. }
  34. configDbContext.SaveChanges();
  35. }
  36. // Generate records corresponding to the api resources
  37. if (!configDbContext.ApiResources.Any())
  38. {
  39. foreach (var api in Config.GetApis())
  40. {
  41. configDbContext.ApiResources.Add(api.ToEntity());
  42. }
  43. configDbContext.SaveChanges();
  44. }
  45. }
  46. }

启动 IdentityServer4

Full Stack 04 - 图4

Google 也用了相似的协议:https://accounts.google.com/.well-known/openid-configuration

可以通过刚才创建的 Alice 和 Bob 进行登录:
Full Stack 04 - 图5

可以在控制台通过 Log 看到发生的一切操作:
Full Stack 04 - 图6

建议阅读 IdentityServer4 的文档
Full Stack 04 - 图7

IdentityServer is middleware that adds the spec compliant OpenID Connect and OAuth 2.0 endpoints to an arbitrary ASP.NET Core application.

如果还有兴趣,也推荐参阅 OAuth 2.0
OAuth 深度相对比较深,但也能更清晰的阐释 IdentityServer4 的底层实现和诸多问题的解决方案。

如果对整体实现还有兴趣,还可以去参阅 OpenID