API key in header with swashbuckle
Update 2021-09-15:
As already noted in Justin Greywolf's comment.
The "In" and "Type" properties have been changed from a string to the ParameterLocation
and SecuritySchemeType
enums:
services.AddSwaggerGen(c =>{
c.SwaggerDoc("v1", new Info { Title = "[anything]", Version = "v1" });
c.AddSecurityDefinition("[auth scheme: same name as defined for asp.net]", new ApiKeyScheme() {
In = ParameterLocation.Header,
Name = "X-API-KEY", //header with api key
Type = SecuritySchemeType.ApiKey,
});
});
Update 2019-04-10:
The paradigm has shifted to accommodate security definitions in the generated swagger.json
Source https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements
services.AddSwaggerGen(c =>{
c.SwaggerDoc("v1", new Info { Title = "[anything]", Version = "v1" });
c.AddSecurityDefinition("[auth scheme: same name as defined for asp.net]", new ApiKeyScheme() {
In = "header", // where to find apiKey, probably in a header
Name = "X-API-KEY", //header with api key
Type = "apiKey", // this value is always "apiKey"
});
});
Original Answer
Check it out:
config
.EnableSwagger(c =>
{
c.ApiKey("apiKey")
.Description("API Key Authentication")
.Name("X-ApiKey")
.In("header");
c.SingleApiVersion("v1", "My API");
})
.EnableSwaggerUi(c => {
c.EnableApiKeySupport("X-ApiKey", "header");
})
You'll have to inject a custom index.html based on the original (as described here) and change the following line in the function addApiKeyAuthorization
:
var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("X-ApiKey", key, "header");