Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we secure Swagger UI with Windows Authentication

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?

like image 521
scarson Avatar asked Oct 28 '25 13:10

scarson


1 Answers

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";
});
like image 132
Adam Avatar answered Oct 31 '25 13:10

Adam