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

╄→гoц情女王★ 提交于 2019-12-12 16:08:02

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/56535077/how-to-force-swagger-swashbuckle-to-append-an-api-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!