如何强制Swagger / Swashbuckle附加API密钥? [英] How to force Swagger/Swashbuckle to append an API key?

查看:496
本文介绍了如何强制Swagger / Swashbuckle附加API密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.NET Core 2.x项目,该项目集成了Swagger和Swashbucklev4.x。

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

但是,现在我需要以www.foo.com/的形式向Swagger触发的每个GET附加一个查询字符串。 myendpoint? authorization = APIKEY 。为此,我在Startup.ConfigureServices中具有以下内容:

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

当我昂首阔步时,它的确显示了一个对话框,并在我输入时成功接受API密钥。但是,所有API调用仍然会在没有查询字符串的情况下消失。

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.

我缺少什么?

< a href = https://i.stack.imgur.com/ucd0t.png rel = nofollow noreferrer>

推荐答案

特别是对于Swashbuckle,(NSwag有自己的注册授权方式流程)仅定义安全性定义是不够的,还需要注册使用该安全性定义的操作。

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.

由于您要将api-key附加到所有操作,您的用例非常简单:只需为您的定义注册安全性要求即可,您可以这样进行:

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[] {} } };

您可以阅读更多有关如何定义,自定义和注册不同授权方案的信息。 s 此处

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

对于即将发布的Swashbuckle v5,可以使用以下代码:

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

这篇关于如何强制Swagger / Swashbuckle附加API密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆