2017-10-16 79 views
1

我在this tutorial後面添加了Swagger和Swashbuckle生成器。現在,當導航到https://localhost:port/swagger/時,我可以看到生成的API文檔。請注意,我還沒有創建任何SwaggerController類 - 這都是由NuGet包處理的。ASP.NET Core 2.0:在沒有控制器的情況下驗證路由

問題是,我的整個網站,甚至是API,都使用自定義LDAP進行身份驗證。我也想保護/swagger/頁面。但是,我沒有找到如何做到這一點。關於StackOverflow的唯一相關問題描述了adding authentication INTO swagger requests - 未驗證整個API文檔頁面。

有沒有具體的方法如何保護生成的/swagger/頁面?或者,是否有向ASP.NET Core 2.0 MVC路由添加驗證驗證器的一般方法?

回答

2

創建自定義的中間件處理程序,然後將其添加到管道象下面這樣:

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
     { 
      if (env.IsDevelopment()) 
      { 
       app.UseDeveloperExceptionPage(); 
      } 
      app.UseMvc(); 
      app.UseStaticFiles(); 

      //And here's where the middleware is registered 
      app.UseRequestAuthHandler(); 
      app.UseSwaggerUI(c => 
      { 
       c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); 
      }); 
     } 

中間件類:

namespace SwaggerDemo.Handlers 
{ 
    using System.Net; 
    using System.Threading.Tasks; 

    using Microsoft.AspNetCore.Builder; 
    using Microsoft.AspNetCore.Http; 

    public class RequestAuthHandler 
    { 
     private const string _swaggerPathIdentifier = "swagger"; 
     private readonly RequestDelegate _next; 

     public RequestAuthHandler(RequestDelegate next) 
     { 
      _next = next; 
     } 

     public async Task Invoke(HttpContext context) 
     { 
      // First check if the current path is the swagger path 
      if (context.Request.Path.HasValue && context.Request.Path.Value.ToLower().Contains(_swaggerPathIdentifier)) 
      { 
       // Secondly check if the current user is authenticated 
       if (!context.User.Identity.IsAuthenticated) 
       { 
        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; 
        return; 
       } 
      } 
      await _next.Invoke(context); 
     } 
    } 

    public static class RequestAuthHandlerExtension 
    { 
     public static IApplicationBuilder UseRequestAuthHandler(this IApplicationBuilder builder) 
     { 
      return builder.UseMiddleware<RequestAuthHandler>(); 
     } 
    } 
} 
相關問題