定义时您需要指定更多选项OpenApiSecurityScheme
.
您可以按照以下步骤进行设置:
- Specify
TokenUrl
。客户端凭证流程有效/token
端点,所以我们必须给它一个正确的 URL。这里我使用了IdentityServer的演示服务器 https://demo.identityserver.io/
- 指定令牌如何发送到后端:我们希望将其发送到
Authorization
标头与Bearer
scheme.
- 指定应用程序需要哪些范围。这是一个映射范围 -> 描述的字典。
- 最后,添加安全要求(此处适用于所有端点),该要求将在端点旁边显示一个锁图标。 (这也有助于其他 OpenAPI 客户端在代码生成期间)
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(
c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ApiPlayground", Version = "v1" });
c.AddSecurityDefinition(
"oauth",
new OpenApiSecurityScheme
{
Flows = new OpenApiOAuthFlows
{
ClientCredentials = new OpenApiOAuthFlow
{
Scopes = new Dictionary<string, string>
{
["api"] = "api scope description"
},
TokenUrl = new Uri("https://demo.identityserver.io/connect/token"),
},
},
In = ParameterLocation.Header,
Name = HeaderNames.Authorization,
Type = SecuritySchemeType.OAuth2
}
);
c.AddSecurityRequirement(
new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{ Type = ReferenceType.SecurityScheme, Id = "oauth" },
},
new[] { "api" }
}
}
);
}
);
}
全部设置完毕后的外观如下:
一旦您进行身份验证,它就会填充令牌:
现在我们可以发送请求,并且 Swagger UI 正如我们所期望的那样在标头中包含令牌:
预填充身份验证弹出窗口
作为最后的修饰,我们可以使用一些默认值预先填充身份验证对话框:
在 - 的里面Startup:Configure
在我们设置 Swagger UI 的方法中,我们可以指定客户端 id + 密钥(这违背了目的,但在本地开发中可能有用)
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiPlayground v1");
c.OAuthClientId("m2m");
c.OAuthClientSecret("secret");
});
参考
- https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements https://github.com/domaindrivendev/Swashbuckle.AspNetCore#add-security-definitions-and-requirements