在 Swagger UI/Swashbuckle 中实施 OpenID Connect 的解决方法

2024-02-22

我有两个不同的项目:

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

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

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


请像这样修改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" } },
                },
            };
        }
    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Swagger UI/Swashbuckle 中实施 OpenID Connect 的解决方法 的相关文章

随机推荐