2017-10-16 44 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>(); 
     } 
    } 
} 
相关问题