API key in header with swashbuckle

Not loved picture Not loved · May 2, 2016 · Viewed 16.9k times · Source

I want to do API key based authentication on a WebAPI project with Swashbuckle (swagger for .net).

I have configured swashbuckle as below:

config
    .EnableSwagger(c =>
    {
        c.ApiKey("apiKey")
            .Description("API Key Authentication")
            .Name("X-ApiKey")
            .In("header");
        c.SingleApiVersion("v1", "My API");

    })
    .EnableSwaggerUi();

(see https://github.com/domaindrivendev/Swashbuckle#describing-securityauthorization-schemes)

It appears to create the swagger file I expect:

   "securityDefinitions": {
      "apiKey": {
        "type": "apiKey",
        "description": "API Key Authentication",
        "name": "X-ApiKey",
        "in": "header"
      }
    }

But when I go to the UI and 'Try it out' it tries to put the API key into the query string (which I think is the default behavior) instead of the headers.

eg:

curl -X POST --header 'Accept: application/json' 'http://localhost:63563/api/MyMethod?api_key=key'

How can I get swagger to use put the API key in the header instead of the query string?

Answer

Keith Ripley picture Keith Ripley · Apr 7, 2017

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