Skip to content

Instantly share code, notes, and snippets.

@ArwynFr
Last active October 9, 2023 11:39
Show Gist options
  • Select an option

  • Save ArwynFr/b79e5c343e15e836f2121cfac80d98ae to your computer and use it in GitHub Desktop.

Select an option

Save ArwynFr/b79e5c343e15e836f2121cfac80d98ae to your computer and use it in GitHub Desktop.
Add OIDC+PKCE to swagger UI

OIDC+PKCE authentication on Swagger UI

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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment