我们如何通过Windows身份验证保护Swagger UI [英] How do we secure Swagger UI with Windows Authentication

查看:49
本文介绍了我们如何通过Windows身份验证保护Swagger UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个.net Core 2.2 Web Api,它使用swagger ui公开Web Api定义.我们希望将此端点仅保护给特定AD组内​​的用户.我们目前正在同时使用Windows和匿名身份验证.问题是我们无法强制Swagger使用Windows身份验证来阻止用户.

We have a .Net Core 2.2 Web Api that uses swagger ui to expose the Web Api definitions. We want to secure this endpoint to only users inside of a certain AD Group. We currently are using Both Windows and Anonymous Authentication. Problem is we cannot enforce Swagger to use Windows Authentication to block users.

有什么想法吗?

推荐答案

尽管令人沮丧,但到目前为止,我发现保护Swagger端点(通过Swashbuckle)的最简单方法只是将其置于自己的路径下,然后使用一个简单的中间件,可以在提供服务之前根据需要验证授权状态.这是为NET Core 3.1编写的,用于检查声明,因此您可能需要调整方案的授权检查.显然,您仍然需要/想要对其文档记录的端点进行授权,但是在任何情况下都不一定希望每个最终用户都可以访问文档.

Although frustrating, the easiest path to securing the Swagger endpoint (via Swashbuckle) I've found thus far is just to put it under its own route and then use a simple middleware to validate the authorization state as you'd like prior to serving it up. This was written for NET Core 3.1 to check against claims, so you may need to adjust the authorization check for your scenario. Obviously, you'll still need/want to require authorization on the endpoints it documents, but you don't necessarily want every end user to have access to the docs in any case.

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";
});

这篇关于我们如何通过Windows身份验证保护Swagger UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆