Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swagger UI, how can I remove the padlock icon from "anonymous" methods?

I'm creating an API with .Net Core 2.1 and using JSON Web Token (JWT) for authentication.

I have 2 controllers: AuthenticationController and UserController. I have decorated AuthenticationController with [AllowAnonymous] and UserController with [Authorize].

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.

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.

Is there a way to remove the padlock icon from those endpoints?

I believe that something can be done with the OperationFilter but I couldn't find a way.

like image 668
g0np Avatar asked Jun 25 '19 01:06

g0np


People also ask

How do I hide the action method in swagger?

By adding this attribute on a controller or action and specifying IgnoreApi = true , it gets hidden from auto-generated documentation. However, this user has to apply this to around 80 controllers.

How do I remove a schema from Swagger UI?

How to do it? add this property in your Swagger UI Options defaultModelsExpandDepth: -1 for hide schema section and for more reference refer this swagger.io/docs/open-source-tools/swagger-ui/usage/… Can you please add your swagger ui configuration settings in your question.

How do I get the swagger authorize button?

In the Swagger Editor (the right pane), click the Authorize button, paste the sample API key shown in the description into the Value field (or use your own OpenWeatherMap API key), and click Authorize. Then click Close to close the authorization modal.


2 Answers

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>();
};

Do not forget to remove any call to AddSecurityRequirement in your Startup.cs, otherwise the padlock icon would still be added to all endpoints.

like image 120
Bruno Martins Avatar answered Sep 19 '22 17:09

Bruno Martins


this solution works for SwashBuckle 5.0.0-rc5 and .Net Core 3.1.1 Web API. You need to :

  1. implement an IOperationFilter interface,
  2. add c.OperationFilter(); in your Startup.cs file
  3. finally remove any call of 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[] {}
          }
        }
      };
    }

  }
}
like image 34
Stephane AmStrong Avatar answered Sep 17 '22 17:09

Stephane AmStrong