【发布时间】:2021-02-26 20:38:29
【问题描述】:
我使用 ASP.Net Core 3.1 创建了一个 API,并使用 Swashbuckle 在站点的根目录添加了 Swagger UI。也许这是一个微不足道的问题,但我希望 Swagger UI 只能由授权用户访问(即不公开)。我已经阅读了很多关于 Swagger 如何处理 API 授权方案的文章,但没有关于 Swagger UI 本身的文章。特别是我需要通过一些[Authorize(Policy="MyCustomPolicy")] 属性或等效属性来限制对它创建的静态文件的访问,因此只有在其身份中具有特定声明的用户才能访问 UI。只有在 Swagger UI 上才需要此条件,因为 API 本身已经通过 Bearer 身份验证进行了访问控制,而且效果很好。
如何将此声明要求添加到 Swagger UI?
这就是我添加 Swagger 服务的方式:
// Register the Swagger Generator service. This service is responsible for genrating Swagger Documents.
// Note: Add this service at the end after AddMvc() or AddMvcCore().
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "MySystem API",
Version = "v1",
Description = "API for MySystem.",
Contact = new OpenApiContact
{
Name = "MyCompany S.A.",
Email = string.Empty,
Url = new System.Uri("https://contoso.com/"),
},
});
var filePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, "MySystem.Web.xml");
c.IncludeXmlComments(filePath);
c.CustomSchemaIds(x => x.GetCustomAttributes(false).OfType<DisplayNameAttribute>().FirstOrDefault()?.DisplayName ?? x.Name);
});
这就是我将 Swagger 添加到构建器的方式:
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "MySystem API v1");
// To serve SwaggerUI at application's root page, set the RoutePrefix property to an empty string.
c.RoutePrefix = string.Empty;
});
提前致谢。
【问题讨论】:
标签: swagger swashbuckle.aspnetcore