Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force Swagger/Swashbuckle to append an API key?

I have a .NET Core 2.x project which integrates Swagger and Swashbuckle v4.x. And it all works really well.

However, now I need to append a query string to every GET that is fired by Swagger in the form of www.foo.com/myendpoint?authorization=APIKEY. To that end, I have the following in Startup.ConfigureServices:

services.AddSwaggerGen(c => {
  c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });

  c.AddSecurityDefinition("api key", new ApiKeyScheme() {
      Description = "Authorization query string expects API key",
      In = "query",
      Name = "authorization",
      Type = "apiKey"
  });
}); 

When I fire up swagger, it does present me with a dialog box and successfully accepts it when I enter the API key. However, all the API calls still go out without the query string.

What am I missing?

enter image description here

like image 787
AngryHacker Avatar asked Jun 11 '19 00:06

AngryHacker


1 Answers

With Swashbuckle in particular, (NSwag has it's own means of registering authorization flows) it's not enough to just define the security definition, you also need to register which operations that use it.

Since you want to append the api-key to all operations, your use case is pretty straight forward: simply register the security requirement for your definition, which you can do so like this:

c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> { { "api key", new[] {} } };

You can read more on how to define, customize, and register different authorization schemes for your operations here.

And for the upcoming v5 of Swashbuckle, the following code could be used:

c.AddSecurityDefinition("api key", new OpenApiSecurityScheme {
    Type = SecuritySchemeType.ApiKey,
    In = ParameterLocation.Query,
    Name = "authorization",
    Description = "Authorization query string expects API key"
});

var key = new OpenApiSecurityScheme() { Name = "api key"};
var requirement = new OpenApiSecurityRequirement {
    { key, new List<string>() }
};
c.AddSecurityRequirement(requirement);
like image 159
Jonathon Chase Avatar answered Nov 14 '22 23:11

Jonathon Chase