【问题标题】:Workaround for implementing OpenID Connect in Swagger UI/ Swashbuckle在 Swagger UI/Swashbuckle 中实现 OpenID Connect 的解决方法
【发布时间】:2020-06-20 10:10:30
【问题描述】:

我有两个不同的项目:

  1. Auth 项目:实现 IdentityServer4 以提供身份验证即服务
  2. API 项目:实现 Swashbuckle.AspNetCore 5.5 以生成 Swagger UI

我在 API 项目中使用 SecuritySchemeType.OpenIdConnect 作为安全方案,每当我点击 Authorize 按钮时,我都会得到一个空的授权模式。我相信问题是因为 Swagger UI 不支持 OpenIDConnect 发现。所以,我只是想知道是否有人找到了解决此问题的方法。

这是一个未解决的问题,可以准确解释我的问题: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1241

【问题讨论】:

  • Swagger UI 3.38.0 现在支持 OpenID Connect。

标签: swagger identityserver4 openid-connect swashbuckle


【解决方案1】:

请像这样修改startup.cs:

c.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
    Flow = "implicit",
    AuthorizationUrl = "https://localhost:44394/connect/authorize"
    Scopes = new Dictionary<string, string>
    {
        { "service", "Service" },
    },
});

c.OperationFilter<ApplyOAuth2Security>();

并添加这个私有方法:

private class ApplyOAuth2Security : IOperationFilter
{
    /// <inheritdoc/>
    public void Apply(Operation operation, OperationFilterContext context)
    {
        var filterDescriptor = context.ApiDescription.ActionDescriptor.FilterDescriptors;
        var isAuthorized = filterDescriptor.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
        var authorizationRequired = context.MethodInfo.CustomAttributes.Any(a => a.AttributeType.Name == "AuthorizeAttribute");

        if (isAuthorized && authorizationRequired)
        {
            operation.Security = new List<IDictionary<string, IEnumerable<string>>>
            {
                new Dictionary<string, IEnumerable<string>>
                {
                     { "oauth2", new string[] { "openid" } },
                },
            };
        }
    }
}

【讨论】:

  • 感谢您的回复。但问题在于 SecuritySchemeType.OpenIdConnect。我可以让它与 SecuritySchemeType.OAuth2 和 ImplicitFlow 完美配合
猜你喜欢
  • 1970-01-01
  • 2018-10-19
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
  • 2015-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多