在带有 ASP.NET Core Swashbuckle 的 Swagger UI 上使用 [Authorize] 属性

Seb*_*son 7 authentication swagger-ui swashbuckle asp.net-core

在 ASP.NET Core 中,使用Swashbuckle.AspNetCore,如何保护对 Swagger UI 的访问与使用 -[Authorize]属性装饰它的方式相同?

[Authorize]当有人试图访问/swagger我的网络应用程序上的-URL时,我希望(等价于)-attribute 执行,就像对于通常装饰的控制器/操作一样,以便AuthenticationHandler<T>执行我的自定义

Ric*_*y G 5

您可以通过简单的中间件解决方案来实现这一点

中间件

public class SwaggerAuthenticationMiddleware : IMiddleware
{
    //CHANGE THIS TO SOMETHING STRONGER SO BRUTE FORCE ATTEMPTS CAN BE AVOIDED
    private const string UserName = "TestUser1";
    private const string Password = "TestPassword1";

    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        //If we hit the swagger locally (in development) then don't worry about doing auth
        if (context.Request.Path.StartsWithSegments("/swagger") && !IsLocalRequest(context))
        {
            string authHeader = context.Request.Headers["Authorization"];
            if (authHeader != null && authHeader.StartsWith("Basic "))
            {
                // Get the encoded username and password
                var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1]?.Trim();

                // Decode from Base64 to string
                var decodedUsernamePassword = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword));

                // Split username and password
                var username = decodedUsernamePassword.Split(':', 2)[0];
                var password = decodedUsernamePassword.Split(':', 2)[1];

                // Check if login is correct
                if (IsAuthorized(username, password))
                {
                    await next.Invoke(context);
                    return;
                }
            }

            // Return authentication type (causes browser to show login dialog)
            context.Response.Headers["WWW-Authenticate"] = "Basic";

            // Return unauthorized
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        }
        else
        {
            await next.Invoke(context);
        }
    }

    private bool IsAuthorized(string username, string password) => UserName == username && Password == password;

    private bool IsLocalRequest(HttpContext context)
    {
        if(context.Request.Host.Value.StartsWith("localhost:"))
            return true;

        //Handle running using the Microsoft.AspNetCore.TestHost and the site being run entirely locally in memory without an actual TCP/IP connection
        if (context.Connection.RemoteIpAddress == null && context.Connection.LocalIpAddress == null)
            return true;

        if (context.Connection.RemoteIpAddress != null && context.Connection.RemoteIpAddress.Equals(context.Connection.LocalIpAddress))
            return true;

        return IPAddress.IsLoopback(context.Connection.RemoteIpAddress);
    }
}
Run Code Online (Sandbox Code Playgroud)

在启动 - >配置(确保在身份验证和授权后添加招摇的东西)

        app.UseAuthentication();
        app.UseAuthorization();

        //Enable Swagger and SwaggerUI
        app.UseMiddleware<SwaggerAuthenticationMiddleware>(); //can turn this into an extension if you ish
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "my test api"));
Run Code Online (Sandbox Code Playgroud)

在启动 -> 配置服务中注册中间件

services.AddTransient<SwaggerAuthenticationMiddleware>();
Run Code Online (Sandbox Code Playgroud)


Mét*_*ule 3

Swagger 中间件完全独立于 MVC 管道,因此不可能开箱即用。然而,通过一些逆向工程,我找到了一个解决方法。它涉及在自定义控制器中重新实现大部分中间件,因此有点复杂,而且显然它可能会因未来的更新而中断。

首先,我们需要停止调用IApplicationBuilder.UseSwaggerand IApplicationBuilder.UseSwaggerUI,这样它就不会与我们的控制器发生冲突。

然后,我们必须通过修改我们的:来添加这些方法添加的所有内容Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("documentName", new Info { Title = "My API", Version = "v1" });
    });

    // RouteTemplate is no longer used (route will be set via the controller)
    services.Configure<SwaggerOptions>(c =>
    {
    });

    // RoutePrefix is no longer used (route will be set via the controller)
    services.Configure<SwaggerUIOptions>(c =>
    {
        // matches our controller route
        c.SwaggerEndpoint("/swagger/documentName/swagger.json", "My API V1");
    });
}


public void Configure(IApplicationBuilder app)
{
    // we need a custom static files provider for the Swagger CSS etc..
    const string EmbeddedFileNamespace = "Swashbuckle.AspNetCore.SwaggerUI.node_modules.swagger_ui_dist";
    app.UseStaticFiles(new StaticFileOptions
    {
        RequestPath = "/swagger", // must match the swagger controller name
        FileProvider = new EmbeddedFileProvider(typeof(SwaggerUIMiddleware).GetTypeInfo().Assembly, EmbeddedFileNamespace),
    });
}
Run Code Online (Sandbox Code Playgroud)

最后,有两件事需要重新实现:文件的生成swagger.json和swagger UI的生成。我们使用自定义控制器来做到这一点:

[Authorize]
[Route("[controller]")]
public class SwaggerController : ControllerBase
{
    [HttpGet("{documentName}/swagger.json")]
    public ActionResult<string> GetSwaggerJson([FromServices] ISwaggerProvider swaggerProvider, 
        [FromServices] IOptions<SwaggerOptions> swaggerOptions, [FromServices] IOptions<MvcJsonOptions> jsonOptions,
        [FromRoute] string documentName)
    {
        // documentName is the name provided via the AddSwaggerGen(c => { c.SwaggerDoc("documentName") })
        var swaggerDoc = swaggerProvider.GetSwagger(documentName);

        // One last opportunity to modify the Swagger Document - this time with request context
        var options = swaggerOptions.Value;
        foreach (var filter in options.PreSerializeFilters)
        {
            filter(swaggerDoc, HttpContext.Request);
        }

        var swaggerSerializer = SwaggerSerializerFactory.Create(jsonOptions);
        var jsonBuilder = new StringBuilder();
        using (var writer = new StringWriter(jsonBuilder))
        {
            swaggerSerializer.Serialize(writer, swaggerDoc);
            return Content(jsonBuilder.ToString(), "application/json");
        }
    }

    [HttpGet]
    [HttpGet("index.html")]
    public ActionResult<string> GetSwagger([FromServices] ISwaggerProvider swaggerProvider, [FromServices] IOptions<SwaggerUIOptions> swaggerUiOptions)
    {
        var options = swaggerUiOptions.Value;
        var serializer = CreateJsonSerializer();

        var indexArguments = new Dictionary<string, string>()
        {
            { "%(DocumentTitle)", options.DocumentTitle },
            { "%(HeadContent)", options.HeadContent },
            { "%(ConfigObject)", SerializeToJson(serializer, options.ConfigObject) },
            { "%(OAuthConfigObject)", SerializeToJson(serializer, options.OAuthConfigObject) }
        };

        using (var stream = options.IndexStream())
        {
            // Inject arguments before writing to response
            var htmlBuilder = new StringBuilder(new StreamReader(stream).ReadToEnd());
            foreach (var entry in indexArguments)
            {
                htmlBuilder.Replace(entry.Key, entry.Value);
            }

            return Content(htmlBuilder.ToString(), "text/html;charset=utf-8");
        }
    }

    private JsonSerializer CreateJsonSerializer()
    {
        return JsonSerializer.Create(new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            Converters = new[] { new StringEnumConverter(true) },
            NullValueHandling = NullValueHandling.Ignore,
            Formatting = Formatting.None,
            StringEscapeHandling = StringEscapeHandling.EscapeHtml
        });
    }

    private string SerializeToJson(JsonSerializer jsonSerializer, object obj)
    {
        var writer = new StringWriter();
        jsonSerializer.Serialize(writer, obj);
        return writer.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)