c# - ASP.NET Core - Swagger - 公共(public)和私有(private) Swagger 页面

标签 c# asp.net-core swagger swagger-ui swashbuckle

我们有一个 API,其中包含一些我们想要公开的端点,以及一些我们不想公开的端点。但是,我不只是想排除私有(private)端点,我仍然希望它们可见,但仅对某些用户或至少在不同的 url 下可见。这似乎应该相当普遍,但我很难找到如何做到这一点。

目前我们已经 Swagger 设置和工作,显示所有端点。一些 Controller 使用 ApiExplorerSettings 标记为“公共(public)”组。像这样的属性(其中 SwaggerGroups.Public 是字符串常量“public”):

[ApiExplorerSettings(GroupName = SwaggerGroups.Public)]

理想情况下,我们会有一个显示所有 Controller /方法标记为公开的 Swagger 页面,以及另一个显示所有端点的密码保护端点。这可能吗?

最佳答案

首先,您的问题听起来像是您没有正确分离 API,实际上它应该是两个 api(微服务术语中的两个应用程序服务)。

因此,您也应该将其视为两个独立的 API。

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("public", new OpenApiInfo { Title = "My Public API", Version = "v1" });
    c.SwaggerDoc("private", new OpenApiInfo { Title = "My Private API", Version = "v1" });
});

这将生成两个不同的 OpenAPI (Swagger) 规范。 /api-docs/public/swagger.json/api-docs/private/swagger.json ,可以托管在两个不同的 UI 应用程序中(一个 protected ,另一个公开可用)
// Public Docs Api
app.UseSwaggerUI(c =>
{
    // we use absolute uri here, since the swagger.json is outside of this application
    c.SwaggerEndpoint("http://example.com/api-docs/public/swagger.json", "Public API");
});


// Private Docs App
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("http://example.com/api-docs/private/swagger.json", "Private API");
});

另一种方法是使用构建管道/持续集成系统。 Swashbuckle.AspNetCore 在 5.x 版本的库中提供了一个 cli 扩展,可以作为构建脚本的一部分执行以生成 swagger.json构建过程中的文件。

例如
dotnet swagger tofile --output ../swagger/myapi/private.json MyCompany.MyApplication.Mvc private
dotnet swagger tofile --output ../swagger/myapi/public.json MyCompany.MyApplication.Mvc public

并拥有一个像这样的文档应用程序
// Private Docs App
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("http://example.com/api-docs/swagger/myapp/private.json", "Private API");
    c.SwaggerEndpoint("http://example.com/api-docs/swagger/myapp/public.json", "Public API");
});

使用 Webserver 保护“private.json”意味着(nginx、apache、iis),即仅允许在内部网络中或仅在身份验证后访问 private.json。

上述方法的替代方法是将两个文件托管在同一个应用程序中,但使用中间件保护私有(private)文件,请参阅 this GitHub issue一些灵感。

关于c# - ASP.NET Core - Swagger - 公共(public)和私有(private) Swagger 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58203007/

相关文章:

asp.net - ASP.NET 5 类库(包)中的 .NET Platform 5.4 是什么?

c# - 如何在 ASP.NET Core 2.2 中创建一个链接来切换语言?

c# - 使用 Swagger 5.0.0-rcX 和 .Net-Core 3 上传文件

c# - 简单注入(inject)器:如何跳过对容器中对象的验证

c# - 在 Windows 窗体中使用带有工作单元和存储库模式的简单注入(inject)器

c# - 通过 Pinvoke 传递 C# 字符串

amazon-web-services - 资源 arn :aws:cloudformation:us-east-1:aws:transform 的权限问题

c# - 延迟执行与 ToList 给出不同的结果

asp.net-core - 将数据传递给 IdentityServer4 中的 IProfileService

swagger - 如何修复 Swagger 编辑器中的 "Path parameter ... must have the corresponding {...} segment in the/path"错误?