Open Closed

Swagger Auth Wall #9084


User avatar
0
Josh created

Hey,

I was wondering if you guys know a method to auth wall off swagger to require users to be logged into the app before accessing the swagger. Do you have any ideas for this?

Kind regards,
Josh.


1 Answer(s)
  • User Avatar
    0
    enisn created
    Support Team .NET Developer

    Hi,

    As the beste practise, we only enable swagger in debug mode by default. But if you need to an authentication, you can go with Basic Authentication and it's something like that:

    public class BasicAuthenticationMiddleware
    {
        private readonly RequestDelegate _next;
    
        public BasicAuthenticationMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    
        public async Task InvokeAsync(HttpContext context)
        {
            // Check if the request path matches /swagger
            if (context.Request.Path.StartsWithSegments("/swagger"))
            {
                if (!context.Request.Headers.ContainsKey("Authorization"))
                {
                    context.Response.Headers["WWW-Authenticate"] = "Basic";
                    context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    return;
                }
    
                var authHeader = context.Request.Headers["Authorization"].ToString();
                if (authHeader.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))
                {
                    var encodedCredentials = authHeader.Substring("Basic ".Length).Trim();
                    var decodedCredentials = Encoding.UTF8.GetString(Convert.FromBase64String(encodedCredentials));
                    var parts = decodedCredentials.Split(':', 2);
                    if (parts.Length == 2 && ValidateCredentials(parts[0], parts[1]))
                    {
                        await _next(context); // Proceed to the next middleware
                        return;
                    }
                }
    
                context.Response.StatusCode = StatusCodes.Status401Unauthorized; // Unauthorized
                return;
            }
    
            // Continue with the pipeline for other requests
            await _next(context);
        }
    
        private bool ValidateCredentials(string username, string password)
        {
            // Replace with your logic to validate credentials
            return username == "admin" && password == "password";
        }
    }
    
    app.UseMiddleware<BasicAuthenticationMiddleware>();
    

    And browser will prompt users for username and password:
    image.png

Boost Your Development
ABP Live Training
Packages
See Trainings
Mastering ABP Framework Book
Do you need assistance from an ABP expert?
Schedule a Meeting
Mastering ABP Framework Book
The Official Guide
Mastering
ABP Framework
Learn More
Mastering ABP Framework Book
Made with ❤️ on ABP v9.3.0-preview. Updated on April 09, 2025, 10:18