How do we secure Swagger UI with Windows Authentication

让人想犯罪 __ 提交于 2021-02-19 06:11:12

问题


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.

Any Ideas?


回答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);
    }
}

And during startup:

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


来源:https://stackoverflow.com/questions/62454751/how-do-we-secure-swagger-ui-with-windows-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!