我们有一个 .Net Core 2.2 Web Api,它使用 swagger ui 来公开 Web Api 定义。我们希望仅向特定 AD 组内的用户保护此端点。我们目前使用 Windows 和匿名身份验证。问题是我们无法强制 Swagger 使用 Windows 身份验证来阻止用户。
有任何想法吗?
虽然令人沮丧,但到目前为止,我发现保护 Swagger 端点(通过 Swashbuckle)的最简单方法就是将其放在自己的路径下,然后在提供服务之前使用简单的中间件来验证授权状态向上。这是为 NET Core 3.1 编写的,用于检查声明,因此您可能需要根据您的场景调整授权检查。显然,您仍然需要/想要要求对其记录的端点进行授权,但您不一定希望每个最终用户在任何情况下都可以访问文档。
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
/// <summary>
/// Middleware to protect API Swagger docs
/// </summary>
public class SwaggerAuthorizationMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public SwaggerAuthorizationMiddleware(RequestDelegate next, ILogger<SwaggerAuthorizationMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
// If API documentation route and user isn't authenticated or doesn't have the appropriate authorization, then block
if (context.Request.Path.StartsWithSegments("/apidoc"))
&& (!context.User.Identity.IsAuthenticated || !context.User.HasClaim("ClaimName", "ClaimValue")))
{
_logger.LogWarning($"API documentation endpoint unauthorized access attempt by [{context.Connection.RemoteIpAddress}]");
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
await _next.Invoke(context);
}
}
并且在启动过程中:
app.UseAuthorization(); // before the middleware
app.UseMiddleware<SwaggerAuthorizationMiddleware>();
app.UseSwagger(c =>
{
c.RouteTemplate = "apidoc/swagger/{documentName}/swagger.json";
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/apidoc/swagger/v1/swagger.json", "My Service");
c.RoutePrefix = "apidoc";
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)