Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Authentication to /swagger/ui/index page - Swagger | Web API | Swashbuckle

I'm working on a Swagger (Web API) project.
When I first run the application it shows the Login page for Swagger UI.
So, a user first has to login to access Swagger UI Page, However, if user directly enters "http://example.com/swagger/ui/index" then he's able to access the Swagger UI page.

afaik the swagger-ui is served by the swashbuckle assembly. The source is not available in my project.

How can I make the user redirect to login page if he's not logged in to Swagger UI page?

like image 361
GorvGoyl Avatar asked Dec 23 '16 05:12

GorvGoyl


People also ask

How do I add an Authorize button in Swagger?

In the Swagger Editor (the right pane), click the Authorize button, paste the sample API key shown in the description into the Value field (or use your own OpenWeatherMap API key), and click Authorize. Then click Close to close the authorization modal.


1 Answers

Finally, I solved it with DelegtingHandler, here's how I did it:
Create a file SwaggerAccessMessageHandler.cs and add it in App_Start folder.

using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class SwaggerAccessMessageHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (IsSwagger(request) && !Thread.CurrentPrincipal.Identity.IsAuthenticated)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Redirect);
            // Redirect to login URL
            string uri = string.Format("{0}://{1}", request.RequestUri.Scheme, request.RequestUri.Authority);    
            response.Headers.Location = new Uri(uri);
            return Task.FromResult(response);
        }
        else
        {
            return base.SendAsync(request, cancellationToken);
        }
    }

    private bool IsSwagger(HttpRequestMessage request)
    {
        return request.RequestUri.PathAndQuery.Contains("/swagger");
    }
}

Next, Wire up the handler in SwaggeConfig.cs just before enabling Swagger as follows:

GlobalConfiguration.Configuration.MessageHandlers.Add(new SwaggerAccessMessageHandler());

GlobalConfiguration.Configuration.EnableSwagger(c =>
{
    ...
});
like image 94
GorvGoyl Avatar answered Oct 20 '22 03:10

GorvGoyl