在 Swagger UI 中,如何从“匿名"中删除挂锁图标?方法? [英] In Swagger UI, how can I remove the padlock icon from "anonymous" methods?
问题描述
我正在使用 .Net Core 2.1 创建一个 API,并使用 JSON Web Token (JWT) 进行身份验证.
I'm creating an API with .Net Core 2.1 and using JSON Web Token (JWT) for authentication.
我有 2 个控制器:AuthenticationController
和 UserController
.我用 [AllowAnonymous]
和 UserController
用 [Authorize]
装饰了 AuthenticationController
.
I have 2 controllers: AuthenticationController
and UserController
.
I have decorated AuthenticationController
with [AllowAnonymous]
and UserController
with [Authorize]
.
Swagger 工作正常:它允许我在不请求授权的情况下访问 AuthenticationController (SignUp/SignIn) 中的端点,并且它确实请求 JWT 访问 UserController
中的端点.
Swagger is working correctly: it allows me to hit the endpoints in AuthenticationController (SignUp/SignIn) without requesting authorization, and it does request JWT to hit the endpoints in UserController
.
但是,在 Swagger UI 中,每个控制器的每个端点都会显示一个挂锁图标,就好像它们都需要授权一样.一切都按预期正常工作,但令我困扰的是,不需要授权的端点仍然显示挂锁图标.
However, in Swagger UI, every endpoint of every controller shows a padlock icon as if all of them required authorization. Everything works correctly and as expected but it just bothers me that the endpoints that don't require authorization still show that padlock icon.
有没有办法从这些端点移除挂锁图标?
我相信使用 OperationFilter
可以做一些事情,但我找不到方法.
I believe that something can be done with the OperationFilter
but I couldn't find a way.
推荐答案
当然,您需要使用 IOperationFilter
来移除匿名端点的挂锁图标.
Absolutly, you need to use an IOperationFilter
to remove the padlock icon for the anonymous endpoints.
// AuthResponsesOperationFilter.cs
public class AuthResponsesOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
.Union(context.MethodInfo.GetCustomAttributes(true))
.OfType<AuthorizeAttribute>();
if (authAttributes.Any())
{
var securityRequirement = new OpenApiSecurityRequirement()
{
{
// Put here you own security scheme, this one is an example
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
};
operation.Security = new List<OpenApiSecurityRequirement> { securityRequirement };
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
}
}
}
// Startup.cs
services.AddSwaggerGen(c =>
{
...
c.OperationFilter<AuthResponsesOperationFilter>();
};
不要忘记删除 Startup.cs
中对 AddSecurityRequirement
的任何调用,否则挂锁图标仍会添加到所有端点.
Do not forget to remove any call to AddSecurityRequirement
in your Startup.cs
, otherwise the padlock icon would still be added to all endpoints.
这篇关于在 Swagger UI 中,如何从“匿名"中删除挂锁图标?方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!