在Swagger UI中,如何从“匿名”方法中删除挂锁图标?

drkbr07n  于 2022-11-06  发布在  其他
关注(0)|答案(4)|浏览(294)

我正在使用.Net Core 2.1创建一个API,并使用JSON Web Token(JWT)进行身份验证。
我有两个控制器:我用[AllowAnonymous]装饰了AuthenticationController,用[Authorize]装饰了UserController
Swagger工作正常:它允许我在不请求授权的情况下访问AuthenticationController(SignUp/SignIn)中的端点,并且它确实请求JWT访问UserController中的端点。
然而,在Swagger UI中,每个控制器的每个端点都显示一个挂锁图标,好像它们都需要授权。一切都正常工作,正如预期的那样,但它只是困扰我的是,不需要授权的端点仍然显示挂锁图标。

是否有办法从这些端点移除挂锁图标?

我相信可以用OperationFilter做一些事情,但我找不到一种方法。

7d7tgy0s

7d7tgy0s1#

当然,您需要使用IOperationFilter来删除匿名端点的挂锁图标。

// 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的任何调用,否则挂锁图标仍将添加到所有端点。

kb5ga3dv

kb5ga3dv2#

此解决方案适用于SwashBuckle 5. 0. 0-rc 5和.Net Core 3. 1. 1 Web API。您需要:
1.实现一个IOperationFilter接口,
1.添加c.操作过滤器();在您的Startup.cs文件中
1.最后删除AddSecurityRequirement任何调用

public class AuthResponsesOperationFilter: 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)) {
      operation.Security = new List < OpenApiSecurityRequirement > {
        new OpenApiSecurityRequirement {
          {
            new OpenApiSecurityScheme {
              Reference = new OpenApiReference {
                Type = ReferenceType.SecurityScheme,
                  Id = "bearer"
              }
            }, new string[] {}
          }
        }
      };
    }

  }
}
deikduxw

deikduxw3#

在startup.cs -〉services.AddSwaggerGen中,您需要添加c.OperationFilter<ApplyOAuth2Security>();并在stratup.cs中添加以下方法,这将在Swagger UI中为标记为仅授权的操作方法启用锁定/授权图标。

private class ApplyOAuth2Security : IOperationFilter
        {
            /// <inheritdoc/>
            public void Apply(Operation operation, OperationFilterContext context)
            {
                var filterDescriptor = context.ApiDescription.ActionDescriptor.FilterDescriptors;
                var isAuthorized = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
                var authorizationRequired = context.MethodInfo.CustomAttributes.Any(a => a.AttributeType.Name == "AuthorizeAttribute");

                if (isAuthorized && authorizationRequired)
                {
                    operation.Security = new List<IDictionary<string, IEnumerable<string>>>
                    {
                        new Dictionary<string, IEnumerable<string>>
                        {
                             { "oauth2", new string[] { "openid" } },
                        },
                    };
                }
            }
        }
g6ll5ycj

g6ll5ycj4#

安装套件
Swashbuckle.AspNetCore.Filters
然后当你记录你的昂首阔步你需要添加下面的行

options.OperationFilter<SecurityRequirementsOperationFilter >();

下面是一个来自.NET6示例

builder.Services.AddSwaggerGen(options => {
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "API",
        Version = "v1",
        Description = "API using .NET 6"
    });
    options.OperationFilter<SecurityRequirementsOperationFilter>();
});

Swagger UI

相关问题