Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
818 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...