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

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

问题描述

我有一个 .NET Core 2.x 项目,它集成了 Swagger 和 Swashbuckle v4.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/myendpoint?authorization=APIKEY 的形式向 Swagger 触发的每个 GET 附加一个查询字符串.为此,我在 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"
  });
}); 

当我启动 swagger 时,它会向我显示一个对话框,并在我输入 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.

我错过了什么?

推荐答案

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

您可以阅读有关如何为您的操作定义、自定义和注册不同授权方案的更多信息 这里.

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天全站免登陆