2

I migrated a project from dotnet core 2.1 to 3.1. Everything is looking good except for the Authorization header not being sent when using swagger ui. I found several SO that attempted to address this issue and this is the result of it.

headers

enter image description here

Startup.cs

   services.AddAuthentication(options =>
   {
      options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
      options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
       options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
      options.RequireHttpsMetadata = (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development") ? false : true;
      options.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
            options.TokenValidationParameters = tokenValidationParameters;
    });


  services.AddSwaggerGen(c =>
  {
   ...
   c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
   {
      Name = "Authorization",
      Type = SecuritySchemeType.ApiKey,
      Scheme = "Bearer",
      BearerFormat = "JWT",
      In = ParameterLocation.Header,
      Description = "JWT Authorization header using the Bearer scheme."
   });
   c.AddSecurityRequirement(new OpenApiSecurityRequirement
     {
       {
         new OpenApiSecurityScheme
         {
           Reference = new OpenApiReference
           {
               Type = ReferenceType.SecurityScheme,
               Id = "Bearer"
           }
         },
         new string[] {}
    }
  });
  c.EnableAnnotations();
  //
  c.OperationFilter<HeaderParametersFilter>();
  ...
  }

In the previous version of Swashbuckle this was handled using IOperationFilter implementation and I left that in place so the token can be entered in the ui. The most promising SO answer was this one, Migrating to Swashbuckle.AspNetCore version 5, where a solution was found but the same configurations didn't work for me.

HeaderParametersFilter : IOperationFilter

  ...
   if (isAuthorized && !allowAnonymous) {
            AddHeader(operation, "Authorization", "access token", "string", true, "Bearer {access token}");        
    }
   ...
    private static void AddHeader(OpenApiOperation operation, string name, string description, string type, bool isRequired, string defaultValue)
    {
        operation.Parameters.Add(new OpenApiParameter
        {
            Name = name,
            In = ParameterLocation.Header,
            Description = description,
            Required = isRequired,
            Schema = new OpenApiSchema
            {
                Type = type,
                Default = new OpenApiString(defaultValue)
            }
        });
    }
Will Lopez
  • 2,089
  • 3
  • 40
  • 64

0 Answers0