[英]AuthorizeCheckOperationFilter in Swagger 5 in ASP.NET Core
I've been using this method in an older version of Swagger:我一直在旧版本的 Swagger 中使用这种方法:
public class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
.Union(context.MethodInfo.GetCustomAttributes(true))
.OfType<AuthorizeAttribute>();
if (authAttributes.Any())
{
operation.Responses.Add("401", new Response { Description = "Unauthorized" });
operation.Security = new List<IDictionary<string, IEnumerable<string>>>
{
new Dictionary<string, IEnumerable<string>>
{
{ "oauth2", new[] { "myscope" } }
}
};
}
}
}
However, now the interface has changed into this:但是,现在界面变成了这样:
public class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
throw new NotImplementedException();
}
}
How do I convert the code?我如何转换代码? :-)
:-)
Many thanks!非常感谢! Gunnar
贡纳尔
You could refer to the official github doc to change like below:您可以参考官方 github 文档进行如下更改:
public class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var authAttributes = context.MethodInfo
.GetCustomAttributes(true)
.OfType<AuthorizeAttribute>()
.Select(attr => attr.Policy)
.Distinct();
if (authAttributes.Any())
{
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
var oAuthScheme = new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
};
operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
[ oAuthScheme ] = authAttributes.ToList()
}
};
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.