您也可以使用 config.AddSecurity ,它似乎更适合它:
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";
};
});
但是,这两种构造都导致了在 Swagger UI 中添加令牌的选项,但没有导致发送 Authorization 标头。当我添加这一行时:
config.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT token"));
有效。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";
};
});
并在配置
app.UseOpenApi();
app.UseSwaggerUi3();