Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API Key Header not sent from SwaggerUI to API #2636

Closed
Montago opened this issue Apr 21, 2023 · 1 comment
Closed

API Key Header not sent from SwaggerUI to API #2636

Montago opened this issue Apr 21, 2023 · 1 comment

Comments

@Montago
Copy link

Montago commented Apr 21, 2023

I've added the SecurityDefinition as well as SecurityRequirements as described here : https://stackoverflow.com/questions/57227912/swaggerui-not-adding-apikey-to-header-with-swashbuckle-5-x

services.AddSwaggerGen(c =>
			{
				c.AddSecurityDefinition("Api Key in Header", new OpenApiSecurityScheme()
				{
					Name = "x-api-key",
					In = ParameterLocation.Header,
					Type = SecuritySchemeType.ApiKey,
					Description = "Authorization by x-api-key inside request's header",
				});

				var key = new OpenApiSecurityScheme()
				{
					Reference = new OpenApiReference
					{
						Type = ReferenceType.SecurityScheme,
						Id = "x-api-key"
					},
					In = ParameterLocation.Header,
					Type = SecuritySchemeType.ApiKey
				};
				
				var requirement = new OpenApiSecurityRequirement
				{
				   { key, new List<string>() }
				};

				c.AddSecurityRequirement(requirement);
			});

which result in the Authorize option pops up in UI:
image

image

However The API Key isn't sent from SwaggerUI to the Endpoint:
image

The header is missing

This is also the case if i inspect the Request.Headers object in the backend.

Am i missing something ?

@Havunen
Copy link

Havunen commented Feb 21, 2024

Hi @Montago

here is working configuration ( I tested it using it DotSwashbuckle but it should work in Swashbuckle too ):

  c.AddSecurityDefinition("ApiKeyHeader", new OpenApiSecurityScheme()
  {
      Name = "x-api-key",
      In = ParameterLocation.Header,
      Type = SecuritySchemeType.ApiKey,
      Description = "Authorization by x-api-key inside request's header",
  });
  c.AddSecurityRequirement(new OpenApiSecurityRequirement{
      {
          new OpenApiSecurityScheme
          {
              Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "ApiKeyHeader" }
          },
          new string[] {}
      }
  });

The security definition needs to be associated with the security requirement

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants