Oks*_*ing 5 jwt swagger swagger-ui swashbuckle
我在 .NET COre API 项目中使用 Swagger。有没有办法在 Swagger UI 中仅对某些端点应用 JWT 身份验证?
我仅将 [Authorize] 属性放在少数调用上(也尝试将 [AllowAnonymous] 放在不需要身份验证的调用上),但是当我打开 Swagger UI 页面时,锁定符号位于所有端点上。
您必须创建一个IOperationFilter
仅将其添加OpenApiSecurityScheme
到某些端点。此博客文章中描述了如何完成此操作(根据同一篇博客文章中的评论针对 .NET Core 3.1 进行了调整)。
就我而言,[Authorize]
如果没有[AllowAnonymous]
显式添加,则所有端点默认为(也在链接的博客文章中进行了描述)。然后我创建以下实现IOperationFilter
:
public class SecurityRequirementsOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (!context.MethodInfo.GetCustomAttributes(true).Any(x => x is AllowAnonymousAttribute) &&
!(context.MethodInfo.DeclaringType?.GetCustomAttributes(true).Any(x => x is AllowAnonymousAttribute) ?? false))
{
operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme {
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "bearer"
}
}, new string[] { }
}
}
};
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您不将所有端点默认为 ,则必须调整 if 语句[Authorize]
。
最后,在我调用的地方services.AddSwaggerGen(options => { ... }
(通常在Startup.cs
)我有以下行:
options.OperationFilter<SecurityRequirementsOperationFilter>();
Run Code Online (Sandbox Code Playgroud)
options.AddSecurityRequirement(...)
请注意,上面的行将替换(大概)同一位置的现有调用。
归档时间: |
|
查看次数: |
1990 次 |
最近记录: |