Обходной путь для реализации OpenID Connect в Swagger UI / Swashbuckle - PullRequest
1 голос
/ 20 июня 2020
• 1000

Я использую SecuritySchemeType.OpenIdConnect в качестве схемы безопасности в проекте API, и всякий раз, когда я нажимаю кнопку Authorize , я получаю пустой модальный режим авторизации. Я считаю, что проблема в том, что OpenIDConnect Discovery не поддерживается в пользовательском интерфейсе Swagger. Итак, мне просто интересно, нашел ли кто-нибудь обходной путь для этой проблемы.

Вот открытая проблема, точно объясните мою проблему: https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1241

1 Ответ

0 голосов
/ 20 июня 2020

Измените файл 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" } },
                        },
                    };
                }
            }
        }

Надеюсь, это сработает для вас.

...