ASP.NET Core Web API SwaggerUI 集成 IdentityServer4 OAuth 授权
创建 IdentityServer 项目
配置 Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddIdentityServer(options => { options.Events.RaiseInformationEvents = true; options.Events.RaiseErrorEvents = true; options.Events.RaiseSuccessEvents = true; options.Events.RaiseFailureEvents = true;
options.Authentication.CheckSessionCookieSameSiteMode = SameSiteMode.Lax; options.Authentication.CookieSameSiteMode = SameSiteMode.Lax; }) .AddDeveloperSigningCredential() .AddInMemoryIdentityResources(Config.IdentityResources) .AddInMemoryApiResources(Config.ApiResources) .AddInMemoryApiScopes(Config.ApiScopes) .AddInMemoryClients(Config.Clients) .AddTestUsers(TestUsers.Users); }
public void Configure(IApplicationBuilder app) { app.UseStaticFiles(); app.UseRouting(); app.UseIdentityServer(); app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); }
|
配置 Config.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| public static class Config { public static List<IdentityResource> IdentityResources => new() { new IdentityResources.OpenId(), new IdentityResources.Profile(), };
public static List<ApiResource> ApiResources => new() {
};
public static List<ApiScope> ApiScopes => new() { new ApiScope("webapi") };
public static List<Client> Clients => new() { new Client() { ClientName = "Swagger UI", ClientId = "swagger", ClientSecrets = { new Secret("swagger".Sha256()) }, AllowedGrantTypes = GrantTypes.Code, RequirePkce = true, RequireConsent = true, RedirectUris = { "http://localhost:5000/swagger/oauth2-redirect.html" }, AllowedCorsOrigins = { "http://localhost:5000" }, AllowedScopes = { IdentityServerConstants.StandardScopes.OpenId, IdentityServerConstants.StandardScopes.Profile, "webapi" }, } }; }
|
创建 WebAPI 项目
配置 Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| services.AddAuthentication("Bearer") .AddJwtBearer("Bearer", options => { options.Authority = authority; options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false }; });
|
最后在 Controller 的 Action 打上 [Authorize]
即可
注意事项
- 为什么 ApiController 加了
[Authorize]
,但 SwaggerUI 中的 Action 最右边没有 一把锁 的图标?
答:因为 [Authorize]
必须加在 ApiController 的 Action 方法上,才能在 SwaggerUI 中展示锁图标(坑)。