在Swagger UI/Swashbuckle中实现OpenID Connect的解决方法 [英] Workaround for implementing OpenID Connect in Swagger UI/ Swashbuckle

查看:195
本文介绍了在Swagger UI/Swashbuckle中实现OpenID Connect的解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的项目:

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

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

I’m using the SecuritySchemeType.OpenIdConnect as a security scheme in the API project and whenever I click on the Authorize button I get an empty authorization modal. I believe the problem is because of the OpenIDConnect Discovery is not supported in the Swagger UI. So, I’m just wondering if anyone found a workaround for this issue.

这是一个未解决的问题,请确切说明我的问题: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1241

Here is an open issue explain my problem exactly: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1241

推荐答案

请按以下方式修改startup.cs:

Please modify startup.cs like this:

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" } },
                },
            };
        }
    }
}

这篇关于在Swagger UI/Swashbuckle中实现OpenID Connect的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆