如何解决我们如何使用 Windows 身份验证 .NET Core 3.1 保护 Swagger UI
我在链接中引用了:How do we secure Swagger UI with Windows Authentication 但它没有显示弹出窗口
我在 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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。