c# - 我们如何使用 Windows 身份验证 .NET Core 3.1 保护 Swagger UI
问题描述
我已经在链接中引用了:我们如何使用 Windows 身份验证保护 Swagger UI但它不显示弹出窗口
我在 Startup.cs 中的代码
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
app.UseMiddleware<SwaggerAuthorizationMiddleware>();
app.UseSwagger();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API cho dự án Trà Sữa Ji Ji");
});
}
else
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API cho dự án Trà Sữa Ji Ji");
});
app.UseHttpsRedirection();
app.UseStaticFiles();
}
还有我在SwaggerAuthorizationMiddleware中的代码
public class SwaggerAuthorizationMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
public SwaggerAuthorizationMiddleware(RequestDelegate next, ILogger<SwaggerAuthorizationMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
// If API documentation route and user isn't authenticated or doesn't have the appropriate authorization, then block
if (context.Request.Path.StartsWithSegments("/swagger") && !context.User.Identity.IsAuthenticated)
{
_logger.LogWarning($"API documentation endpoint unauthorized access attempt by [{context.Connection.RemoteIpAddress}]");
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
await _next.Invoke(context);
}
}
解决方案
推荐阅读
- python - 如何在 Ansible 任务中注册 python 变量
- docker - Dockerfile 问题导致“curl (56) Recv failure”
- google-cloud-datastore - Dataflow 状态处理中的 Exactly-once 语义
- graphql - 具有不同 API 版本的客户端上的 graphql 查询
- ruby-on-rails - 生成新模型时如何指定belongs_to 和has_many 关系
- android - 如何制作不同形状的布局
- c++ - 在 C++ 中访问列表中的列表
- javascript - 在 JS 中传递输入参数显示意外的输入结束
- python - 安装成功后导入tensorflow时出错
- go - 如何使用 go-swagger 服务 websocket?