【问题标题】:Swagger UI - authentication only for some endpointsSwagger UI - 仅对某些端点进行身份验证
【发布时间】:2020-04-26 14:51:03
【问题描述】:

我在 .NET COre API 项目中使用 Swagger。 有没有办法在 Swagger UI 中仅对某些端点应用 JWT 身份验证?

我只将 [Authorize] 属性放在几个调用上(也尝试将 [AllowAnonymous] 放在不需要身份验证的调用上),但是当我打开 Swagger UI 页面时,锁定符号位于所有端点上.

【问题讨论】:

    标签: swagger swagger-ui swashbuckle jwt-auth


    【解决方案1】:

    您必须创建一个 IOperationFilter 才能仅将 OpenApiSecurityScheme 添加到某些端点。 in this blog post 描述了如何做到这一点(针对 .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[] { }
                        }
                    }
                };
            }
        }
    }
    

    如果您不将所有端点默认为[Authorize],则必须调整 if 语句。

    最后,我打电话给services.AddSwaggerGen(options =&gt; { ... }(通常在Startup.cs)我有以下行:

    options.OperationFilter<SecurityRequirementsOperationFilter>();
    

    请注意,上述行将替换(可能)在同一位置对options.AddSecurityRequirement(...) 的现有调用。

    【讨论】:

    • 这真的很有帮助!我必须使用 Id = "Bearer" 来匹配 Startup.cs 中的代码:c.AddSecurityDefinition("Bearer", ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多