源视频教程:https://www.bilibili.com/video/BV1sJ41197af

一、Ids4基本概念

1.1-什么IdentityServer4?

IdentityServer是基于OpenID Connect的协议标准的身份认证和授权程序,他实现了OpenID Connect和Oauth 2.0协议。
image.png

1.2-IdentityServer4能做什么?

image.png

1.3-IdentityServer4知识点?

1)常见术语解析:
image.png
2)JWT与OAuth2.0:
image.pngimage.png
image.png
3)常见的4种授权模式:
image.png

1.4-OpenID、OpenIDConnct、OAuth的区别?

image.png

1.5-IdentityServer4常用的几种模式

image.png
image.png

1.6-如何快速入门?

image.png
image.png

1.7-Ids4优劣势

image.png

二、快速搭建Ids4基础项目并生成Token

image.png
image.png

命令: dotnet new -i IdentityServer4.Templates

(1)创建项目,然后引用Nuget包。
image.png
image.png
(2)【Program.cs】

  1. public class Program
  2. {
  3. public static int Main(string[] args)
  4. {
  5. //Serilog
  6. Log.Logger = new LoggerConfiguration()
  7. .MinimumLevel.Debug()
  8. .MinimumLevel.Override("Microsoft", LogEventLevel.Error)
  9. .MinimumLevel.Override("System", LogEventLevel.Error)
  10. .MinimumLevel.Override("Microsoft.AspNetCore.Authentication", LogEventLevel.Information)
  11. .Enrich.FromLogContext()
  12. .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Leve1}] {SourceContext} {NewLine} {Message:1j} {NewLine}{Exception} {NewLine}", theme: AnsiConsoleTheme.Literate)
  13. .WriteTo.File(Path.Combine("Logs", @"logs.log"),rollingInterval:RollingInterval.Infinite)
  14. .CreateLogger();
  15. try
  16. {
  17. Log.Information("Starting host...");
  18. //创建一个宿主
  19. CreateHostBuilder(args).Build().Run();
  20. return 0;
  21. }
  22. catch (Exception ex) {
  23. Log.Fatal("Host terminated " + ex.Message);
  24. return 1;
  25. }
  26. finally
  27. {
  28. //关闭日志
  29. Log.CloseAndFlush();
  30. }
  31. }
  32. public static IHostBuilder CreateHostBuilder(string[] args) =>
  33. Host.CreateDefaultBuilder(args)
  34. .ConfigureWebHostDefaults(webBuilder =>
  35. {
  36. webBuilder.UseStartup<Startup>();
  37. //使用Serilog日志接管Ilog
  38. webBuilder.UseSerilog();
  39. });
  40. }

(3)【Startup.cs】

  1. public class Startup
  2. {
  3. // This method gets called by the runtime. Use this method to add services to the container.
  4. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  5. public void ConfigureServices(IServiceCollection services)
  6. {
  7. var builder = services.AddIdentityServer()
  8. .AddInMemoryIdentityResources(Config.Ids)
  9. //用户
  10. .AddTestUsers(Config.Users)
  11. //资源API
  12. .AddInMemoryApiResources(Config.Apis)
  13. //客户端
  14. .AddInMemoryClients(Config.Clients);
  15. //开发环境-添加证书
  16. builder.AddDeveloperSigningCredential();
  17. //配置认证证书服务
  18. services.AddAuthentication();
  19. }
  20. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  21. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  22. {
  23. if (env.IsDevelopment())
  24. {
  25. app.UseDeveloperExceptionPage();
  26. }
  27. app.UseRouting();
  28. //中间件配置
  29. app.UseIdentityServer();
  30. app.UseEndpoints(endpoints =>
  31. {
  32. endpoints.MapGet("/", async context =>
  33. {
  34. await context.Response.WriteAsync("Hello World!");
  35. });
  36. });
  37. }

(3)【Config.cs】

  1. public static IEnumerable<IdentityResource> Ids =>
  2. new IdentityResource[]
  3. {
  4. new IdentityResources.OpenId()
  5. };
  6. /// <summary>
  7. /// API资源
  8. /// </summary>
  9. public static IEnumerable<ApiResource> Apis => new ApiResource[] {
  10. //添加一个API资源
  11. new ApiResource("blog.core.api","Blog.Core API")
  12. };
  13. /// <summary>
  14. /// 客户端信息
  15. /// </summary>
  16. public static IEnumerable<Client> Clients => new Client[] {
  17. //客户端信息
  18. new Client
  19. {
  20. ClientId="blog",//定义客户端ID
  21. ClientSecrets=new[]{ new Secret("secret".Sha256())},//Client用来获取Token
  22. //这里是使用用户名密码和ClientCredentials来换取token的方式,
  23. //ClientCredentials允许Client只使用ClientSecrets来获取token,这种方式适合呢种没有用于参与的api动作。
  24. AllowedGrantTypes=GrantTypes.ResourceOwnerPasswordAndClientCredentials,
  25. AllowedScopes=new[]{ "blog.core.api" }//允许访问的API资源
  26. }
  27. };
  28. /// <summary>
  29. /// 用户信息
  30. /// </summary>
  31. public static List<TestUser> Users =>
  32. new List<TestUser>{
  33. new TestUser
  34. {
  35. SubjectId="1",
  36. Username="admin",
  37. Password="admin"
  38. }
  39. };

三、Ids4持久化操作

image.png

一、迁移项目( 使用 Package Manager Console ): 1、add-migration InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb 2、add-migration InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb 3、add-migration AppDbMigration -c ApplicationDbContext -o Data

4、update-database -context PersistedGrantDbContext
5、update-database -context ConfigurationDbContext
6、update-database -context ApplicationDbContext

—针对:Kimi.OAuth/Web

1、add-migration InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o EntityFrameworkCore/DbContext/Migrations/IdentityServer/PersistedGrantDb 2、add-migration InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o EntityFrameworkCore/DbContext/Migrations/IdentityServer/ConfigurationDb 3、add-migration AppDbMigration -c ApplicationDbContext -o EntityFrameworkCore/DbContext/Migrations/ApplicationUser

四、数据库全表解析

4.1-操作部分

image.png

4.2-配置部分(资源)

//Identityxxx(3)
image.png

//APIxxx(6)
image.png

//Clientxxx(10)
image.png

五、认证中心之内外加权

image.png