谁能知道我如何将基本身份验证与 swashbuckle api 的文档集成?
我看到swaggerconfig文件中有一个basicAuth函数:
c.BasicAuth("basic").Description("Basic HTTP Authentication");
我做了什么:
- 取消注释前一行,但没有任何改变!
有谁知道我错过了什么?
谢谢!
谁能知道我如何将基本身份验证与 swashbuckle api 的文档集成?
我看到swaggerconfig文件中有一个basicAuth函数:
c.BasicAuth("basic").Description("Basic HTTP Authentication");
我做了什么:
有谁知道我错过了什么?
谢谢!
@MarwaAhmad 最出色的答案的一个小改进是检查空参数(例如,简单的 GET 或使用 URL 中的所有参数调用)。还添加了基本身份验证的详细信息。
此外,如果您已经使用全局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"
});
}
}
}
这是我进行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。