Restricting Access to Routes without [Authorize] Filter
Locking down Swagger, Elmah, and other "magic" endpoints
Create a Delegating Handler
In this example, I want to lock down the \swagger
endpoint from an ASP.NET 4.6.1 MVC web application.
public class SwaggerAccessMessageHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (IsSwagger(request) && !Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
var response = request.CreateResponse(HttpStatusCode.Unauthorized);
return Task.FromResult(response);
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
private bool IsSwagger(HttpRequestMessage request)
{
return request.RequestUri.PathAndQuery.StartsWith("/swagger");
}
}
Configure the HttpConfiguration to add the Delegating Handler
In this case, it makes sense to add the handler in the SwaggerConfig file, where Swagger is being configured.
NOTE: In this example, the Swagger Config is explicitly called in the OWIN middleware setup, which is not the default behavior when installing swashbuckle.
public class SwaggerConfig
{
public static void Register(HttpConfiguration config)
{
config.MessageHandlers.Add(new SwaggerAccessMessageHandler());
config.EnableSwagger( ... ); // configuration omitted
}
}
Like this article?
0
Software Development Nerd