我有一个ASP.NET Core 2.2 Web Api,并且通过nswag添加了全面支持。 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}"
}
);
});
//...
}
挥动页面中的按钮
用于复制/粘贴不记名令牌的表格
我正在寻找一种自动化流程并设置访问令牌而无需复制/粘贴的方法。
是否可以设置nswag来做到这一点?
答案 0 :(得分:2)
您可以在generator和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"));
}
);
配置:
app.UseOpenApi();
app.UseSwaggerUi3(settings =>
{
settings.OAuth2Client = new OAuth2ClientSettings
{
ClientId = "demo_api_swagger",
AppName = "Demo API - Swagger",
};
});
在身份服务器4中,注册api:
public static IEnumerable<ApiResource> GetApis()
{
return new List<ApiResource>
{
new ApiResource("api1", "My API")
};
}
还有客户:
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" }
},
在UI中单击Authorize
按钮后,您可以使用IDS4进行身份验证并获取api的访问令牌,然后该令牌将在进行api请求时自动追加到授权请求标头。