You can use config.AddSecurity as well and it seems a bit more designed for it:
services.AddSwaggerDocument(config => {
config.AddSecurity("JWT token", new OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.ApiKey,
Name = "Authorization",
Description = "Copy 'Bearer ' + valid JWT token into field",
In = OpenApiSecurityApiKeyLocation.Header
});
config.PostProcess = (document) =>
{
document.Info.Version = "v1";
document.Info.Title = "MyRest-API";
document.Info.Description = "ASP.NET Core 3.1 MyRest-API";
};
});
However, both constructions resulted in an option to add a token in the Swagger UI, but didn't result in sending the Authorization header. When I added this line:
config.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT token"));
it worked. The complete code in ConfigureServices:
services.AddSwaggerDocument(config => {
config.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT token"));
config.AddSecurity("JWT token", new OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.ApiKey,
Name = "Authorization",
Description = "Copy 'Bearer ' + valid JWT token into field",
In = OpenApiSecurityApiKeyLocation.Header
});
config.PostProcess = (document) =>
{
document.Info.Version = "v1";
document.Info.Title = "MyRest-API";
document.Info.Description = "ASP.NET Core 3.1 MyRest-API";
};
});
And in Configure
app.UseOpenApi();
app.UseSwaggerUi3();