![](/img/trans.png)
[英]How to secure generated API documentation using swagger swashbuckle
[英]How to force Swagger/Swashbuckle to append an API key?
我有一個 .NET Core 2.x 項目,它集成了 Swagger 和 Swashbuckle v4.x。 這一切都非常有效。
但是,現在我需要向 Swagger 以 www.foo.com/myendpoint 的形式觸發的每個 GET 附加一個查詢字符串? authorization=APIKEY
。 為此,我在 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 調用仍會在沒有查詢字符串的情況下發出。
我錯過了什么?
特別是對於 Swashbuckle,(NSwag 有它自己的注冊授權流的方法)僅僅定義安全定義是不夠的,您還需要注冊使用它的操作。
由於您想將 api-key 附加到所有操作,因此您的用例非常簡單:只需為您的定義注冊安全要求,您可以這樣做:
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> { { "api key", new[] {} } };
您可以在此處閱讀有關如何為您的操作定義、自定義和注冊不同授權方案的更多信息。
對於即將發布的 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.