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.
Markdown supported.
Copy, paste, or drag & drop images and files (max 100 MB per file, 100 MB total per post)
1 Answer(s)
-
0
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>();Markdown supported.Copy, paste, or drag & drop images and files (max 100 MB per file, 100 MB total per post)
