gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:12:36 27 4
gpt4 key购买 nike

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

我想要(相当于)[Authorize] -attribute 执行,就像通常装饰的 Controller / Action ,当有人试图访问 /swagger 时-我的网络应用上的 URL,以便我的自定义 AuthenticationHandler<T>被执行 .

最佳答案

Swagger 中间件完全独立于 MVC 管道,因此无法开箱即用。但是,通过一些逆向工程,我找到了一种解决方法。它涉及在自定义 Controller 中重新实现大部分中间件,因此有点复杂,显然它可能会随着 future 的更新而中断。

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

然后,我们必须通过修改 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),
});
}

最后,有两件事需要重新实现: swagger.json 的生成文件,以及 swagger UI 的生成。我们使用自定义 Controller 执行此操作:

[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();
}
}

关于authentication - 在带有 ASP.NET Core Swashbuckle 的 Swagger UI 上使用 [Authorize] 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58283386/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com