【发布时间】:2019-03-16 17:09:52
【问题描述】:
我在 .net core 2.1 中构建了一个 api。为了限制对各种端点的访问,我使用了 IdentityServer4 和 [Authorize] 属性。但是,我在开发过程中的目标是向我们的开发人员公开 api swagger 文档,以便他们无论在哪里工作都可以使用它。我面临的挑战是如何保护 swagger index.html 文件,以便只有他们可以看到 api 的详细信息。
我在 wwwroot/swagger/ui 文件夹中创建了一个自定义 index.html 文件,并且一切正常,但是,该文件使用来自不受保护的 /swagger/v1/swagger.json 端点的数据。我想知道如何覆盖该特定端点的返回值,以便我可以添加自己的身份验证?
编辑:
目前,我已经通过以下中间件实现了上述目标:
public class SwaggerInterceptor
{
private readonly RequestDelegate _next;
public SwaggerInterceptor(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var uri = context.Request.Path.ToString();
if (uri.StartsWith("/swagger/ui/index.html"))
{
var param = context.Request.QueryString.Value;
if (!param.Equals("?key=123"))
{
context.Response.StatusCode = 404;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync("{\"result:\" \"Not Found\"}", Encoding.UTF8);
return;
}
}
await _next.Invoke(context);
}
}
public class Startup
{
//omitted code
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<SwaggerInterceptor>();
//omitted code
}
}
我不喜欢这种方法,因为它会检查每个请求。有没有更好的方法来实现这一目标?以上仅保护 index.html 文件,但我可以对其进行调整以以类似方式保护 json 端点。
【问题讨论】:
-
注意:检查每一个请求是一个非常“便宜”的操作。此外,任何希望使用 Swashbuckle 和 OpenIdConnect 的人请参阅 stackoverflow.com/a/65094653/6795110
标签: c# api swagger asp.net-core-2.0 swagger-ui