How do I set up Swashbuckle and Swagger UI to Authorize using Open ID Connect Discovery (in my case, to Azure AD)?
Here's my (not-fully-working) SwaggerGen setup so far, based on https://stackoverflow.com/a/66147996/7453 :
SwaggerGenOptions c => {
OpenApiInfo apiInfo = new() { /* ...snip... */ };
c.SwaggerDoc("v1", apiInfo);
IncludeXmlFileForSwagger(c);
// Defines the Open ID Connect discovery scheme - see also https://stackoverflow.com/a/66147996/7453
OpenApiSecurityScheme mainScheme = new()
{
Type = SecuritySchemeType.OpenIdConnect,
OpenIdConnectUrl = new Uri($"https://login.microsoftonline.com/{myTenantId}/.well-known/openid-configuration"),
};
c.AddSecurityDefinition("OpenIdConnect", mainScheme);
// Adds a reference to the above scheme as required for every API action (we can get more nuanced later)
// Note: if just try to use mainScheme instead, it doesn't apply a Bearer token)
OpenApiSecurityScheme securityScheme = new() {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme, Id = "OpenIdConnect"
}
};
OpenApiSecurityRequirement securityRequirements = new() { {securityScheme, Array.Empty<string>()} };
c.AddSecurityRequirement(securityRequirements);
}
...and in the static configure method, I have...
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyService v1");
c.OAuthClientId(myClientId);
c.OAuthUsePkce();
});
So the above code lets me authenticate and check a scope called "openid" and shows the "locked" padlock". When I try to run a action via the Swagger UI, it supplies a Bearer token but it comes back invalid.
Do I need to somehow specify an explicit named scope, rather than "openid"? How?
Is my setup even right? If so, why isn't the token valid? Any ideas for troubleshooting?