首页 > 解决方案 > 我们如何使用 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);
    }
}

标签: c#swagger-uiwindows-authenticationasp.net-core-3.1swashbuckle.aspnetcore

解决方案


推荐阅读