Ton*_*nyc 5 swagger identityserver4 asp.net-core-webapi nswag asp.net-core-2.2
我有一个 ASP.NET Core 2.2 Web Api,我用 nswag 添加了 swagger 支持。Web api 使用生成访问令牌的本地 IdentityServer4 进行保护。
我找到了添加授权按钮和表单并在标题中设置不记名令牌的代码。它有效!
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddSwaggerDocument(config =>
{
config.DocumentName = "OpenAPI 2";
config.OperationProcessors.Add(new OperationSecurityScopeProcessor("JWT Token"));
config.AddSecurity("JWT Token", Enumerable.Empty<string>(),
new OpenApiSecurityScheme()
{
Type = OpenApiSecuritySchemeType.ApiKey,
Name = "Authorization",
In = OpenApiSecurityApiKeyLocation.Header,
Description = "Copy this into the value field: Bearer {token}"
}
);
});
//...
}
Run Code Online (Sandbox Code Playgroud)
Swagger 页面中的按钮
不记名令牌的复制/粘贴表格
我正在寻找一种无需复制/粘贴即可自动化流程和设置访问令牌的方法。
是否可以设置 nswag 来执行此操作?
您可以在生成器和 Swagger UI 中启用身份验证。要在 web api 中添加 OAuth2 身份验证(OpenAPI 3):
services.AddOpenApiDocument(document =>
{
document.AddSecurity("bearer", Enumerable.Empty<string>(), new OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.OAuth2,
Description = "My Authentication",
Flow = OpenApiOAuth2Flow.Implicit,
Flows = new OpenApiOAuthFlows()
{
Implicit = new OpenApiOAuthFlow()
{
Scopes = new Dictionary<string, string>
{
{"api1", "My API"}
},
TokenUrl = "http://localhost:5000/connect/token",
AuthorizationUrl = "http://localhost:5000/connect/authorize",
},
}
});
document.OperationProcessors.Add(
new AspNetCoreOperationSecurityScopeProcessor("bearer"));
}
);
Run Code Online (Sandbox Code Playgroud)
配置 :
app.UseOpenApi();
app.UseSwaggerUi3(settings =>
{
settings.OAuth2Client = new OAuth2ClientSettings
{
ClientId = "demo_api_swagger",
AppName = "Demo API - Swagger",
};
});
Run Code Online (Sandbox Code Playgroud)
在身份服务器 4 中,注册 api :
public static IEnumerable<ApiResource> GetApis()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
Run Code Online (Sandbox Code Playgroud)
和客户:
new Client {
ClientId = "demo_api_swagger",
ClientName = "Swagger UI for demo_api",
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true,
RedirectUris = {"https://localhost:44304/swagger/oauth2-redirect.html"},
AllowedScopes = { "api1" }
},
Run Code Online (Sandbox Code Playgroud)
点击AuthorizeUI 中的按钮后,您可以使用 IDS4 进行身份验证并获取 api 的访问令牌,然后在发出 api 请求时令牌将自动附加到授权请求头中。
| 归档时间: |
|
| 查看次数: |
5739 次 |
| 最近记录: |