我们如何使用 Windows 身份验证 .NET Core 3.1 保护 Swagger UI

问题描述

我期待

enter image description here

我在链接中引用了:How do we secure Swagger UI with Windows Authentication 但它没有显示弹出窗口

enter image description here

我在 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 (将#修改为@)