This Gist contains code that allows an ASP.NET 7 WebAPI with Swashbuckle OpenAPI Swagger UI to authenticate agains a PKCE enabled OIDC provider.
It was tested with the following libraries :
-
Swashbuckle.AspNetCore 6.5.0
| using Microsoft.OpenApi.Models; | |
| var builder = WebApplication.CreateBuilder(args); | |
| builder.Services.AddSwaggerGen(options => | |
| { | |
| var scheme = new OpenApiSecurityScheme | |
| { | |
| In = ParameterLocation.Header, | |
| Name = "Authorization", | |
| Flows = new OpenApiOAuthFlows | |
| { | |
| AuthorizationCode = new OpenApiOAuthFlow | |
| { | |
| AuthorizationUrl = new Uri("https://localhost:5001/connect/authorize"), | |
| TokenUrl = new Uri("https://localhost:5001/connect/token") | |
| } | |
| }, | |
| Type = SecuritySchemeType.OAuth2 | |
| }; | |
| options.AddSecurityDefinition("OAuth", scheme); | |
| options.AddSecurityRequirement(new OpenApiSecurityRequirement | |
| { | |
| { | |
| new OpenApiSecurityScheme | |
| { | |
| Reference = new OpenApiReference { Id = "OAuth", Type = ReferenceType.SecurityScheme } | |
| }, | |
| new List<string> { } | |
| } | |
| }); | |
| }); | |
| var app = builder.Build(); | |
| app.UseSwagger(); | |
| app.UseSwaggerUI(options => | |
| { | |
| options.OAuthClientId("api-swagger"); | |
| options.OAuthScopes("profile", "openid"); | |
| options.OAuthUsePkce(); | |
| }); | |
| app.Run(); |