【问题标题】:How to force Swagger/Swashbuckle to append an API key?如何强制 Swagger/Swashbuckle 附加 API 密钥?
【发布时间】:2019-10-25 08:48:21
【问题描述】:

我有一个集成了 Swagger 和 Swashbuckle v4.x 的 .NET Core 2.x 项目。这一切都非常有效。

但是,现在我需要将查询字符串附加到 Swagger 以 www.foo.com/myendpoint?authorization=APIKEY 的形式触发的每个 GET。为此,我在 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"
  });
}); 

当我启动 swagger 时,它会显示一个对话框,并在我输入 API 密钥时成功接受它。但是,所有的 API 调用仍然没有查询字符串。

我错过了什么?

【问题讨论】:

  • 添加定义后添加c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> { { "api key", new [] {} }};会怎样?这应该表明所有操作都应该通过该定义。
  • @JonathonChase 成功了,谢谢先生!

标签: c# .net-core swagger swashbuckle


【解决方案1】:

尤其是 Swashbuckle,(NSwag 有自己的注册授权流程的方法)仅仅定义安全定义是不够的,您还需要注册使用它的操作。

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

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

您可以阅读更多关于如何为您的操作定义、自定义和注册不同的授权方案here

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

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

【讨论】:

  • 您是否偶然知道 Swashbuckle 新 v5 的语法?它似乎根本没有 ApiKeyScheme 类。看起来它已经升级到 Microsoft.OpenApi.Models.OpenApiSecurityScheme 库了。
  • @AngryHacker 我没有,我最近一直在使用 NSwag 包装器。我不相信你需要改变太多。我相信 ApiKey 现在是 AuthorizationCode,您可以将其定义为使用中的 Flow。
  • 我想通了。添加了你的答案。
猜你喜欢
  • 2018-07-29
  • 2018-10-16
  • 2011-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多