首页 > 解决方案 > 如何使用登录页面保护 ASP.NET Core 2.2 Web Api Swagger?

问题描述

通过使用 swagger 的 netcore 2.2 web api 有什么方法可以在用户看到那些 api 文档之前保护我的 api 文档,然后他们会去登录>然后 api 文档。

更多的权力堆栈溢出。希望任何人都可以帮助..

标签: asp.net-coreasp.net-web-apiswaggerswagger-ui

解决方案


如果用户在想要访问 swagger 索引页面时未通过身份验证,您可以创建一个自定义中间件以重定向到登录:

public class SwaggerAuthorizedMiddleware
{
    private readonly RequestDelegate _next;

    public SwaggerAuthorizedMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        //Add your condition
        if (context.Request.Path.StartsWithSegments("/swagger")
            && !context.User.Identity.IsAuthenticated)
        {
            context.Response.Redirect("/Identity/Account/Login");

            await Task.CompletedTask;
        }
        else
        {
            await _next.Invoke(context);
        }

    }
}
public static class SwaggerAuthorizeExtensions
{
    public static IApplicationBuilder UseSwaggerAuthorized(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<SwaggerAuthorizedMiddleware>();
    }
}

在启动配置中:

app.UseAuthentication();           

app.UseSwaggerAuthorized();

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");

});

推荐阅读