我在 this tutorial 之后将 Swagger 和 Swashbuckle 生成器添加到我的站点.现在,当导航到 https://localhost:port/swagger/
时,我可以看到生成的 API 文档。请注意,我没有创建任何 SwaggerController
类 - 这全部由 NuGet 包处理。
问题是,我的整个网站,甚至是 API,都是使用自定义 LDAP 进行身份验证的。我也想保护 /swagger/
页面。但是,我没有找到如何做到这一点的方法。 StackOverflow 上唯一的相关问题描述了 adding authentication INTO swagger requests - 不验证整个 API 文档页面。
是否有特定的方法来保护生成的 /swagger/
页面?或者,是否有向 ASP.NET Core 2.0 MVC 路由添加身份验证验证器的通用方法?
最佳答案
创建自定义中间件处理程序,然后将其添加到管道中,如下所示:
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthorization();
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>();
}
}
}
关于c# - ASP.NET 核心 2.0 : Authenticate a route without a controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46775629/