有谁知道如何将基本的auth与swashbuckle api的文档集成?
我看到swaggerconfig文件中有一个basicAuth函数:
c.BasicAuth("basic").Description("Basic HTTP Authentication");
我做了什么:
有没有人知道我错过了什么?
谢谢!
答案 0 :(得分:6)
以下是我进行httpbasic身份验证的方法:
public class AddAuthorizationHeaderParameterOperationFilter: IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
var isAuthorized = filterPipeline
.Select(filterInfo => filterInfo.Instance)
.Any(filter => filter is IAuthorizationFilter);
var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (isAuthorized && !allowAnonymous)
{
operation.parameters.Add(new Parameter {
name = "Authorization",
@in = "header",
description = "access token",
required = true,
type = "string"
});
}
}
}
api的用户应写入字段值:basic [un:pw] .tobase64。
答案 1 :(得分:5)
@MarwaAhmad最优秀答案的一个小改进是检查空参数(例如简单的GET或URL中所有参数的调用)。还添加了Basic Auth。
的详细信息此外,如果您已经使用全局IAuthorizationFilter
来强制执行HTTPS,那么您将需要更改更通用的
filter => filter is IAuthorizationFilter
到特定的
filter => filter is AuthorizeAttribute
public class AddAuthorizationHeaderParameterOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Instance)
.Any(filter => filter is IAuthorizationFilter);
var allowAnonymous =
apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (isAuthorized && !allowAnonymous)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
operation.parameters?.Add(new Parameter
{
name = "Authorization",
@in = "header",
description = "Basic HTTP Base64 encoded Header Authorization",
required = true,
type = "string"
});
}
}
}