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

前端 未结 3 742
遇见更好的自我
遇见更好的自我 2021-02-14 20:06

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

相关标签:
3条回答
  • 2021-02-14 20:48

    spring-security login page

    in my case, that is not swagger page but spring-security login page. boot version 2.X includes security auto configuration, so if you add spring-security plugin in build.gradle, remove and restart.

    0 讨论(0)
  • 2021-02-14 20:58

    You can take a look this link which describes how to lock down the Swagger UI so that only authenticated users can see it

    http://knowyourtoolset.com/2015/09/secure-web-apis-with-swagger-swashbuckle-and-oauth2-part-4/

    0 讨论(0)
  • 2021-02-14 21:02

    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 =>
    {
        ...
    });
    
    0 讨论(0)
提交回复
热议问题