Авторизация Swagger с настройкой Okta JWT токен - PullRequest
0 голосов
/ 02 октября 2019

Я пытаюсь авторизовать API swagger с конфигурацией okta, используя ASP.NET core 2.2.

Следовал инструкции по этой ссылке https://app.swaggerhub.com/help/enterprise/user-management/sso/okta

Но совершенно не уверен, как мне это сделатьсделай это.

Okta link

https://developer.okta.com/quickstart/?_ga=2.180885607.1554519477.1569975022-1481902663.1569975022#/angular/dotnet/aspnetcore

вот мой код Asp.net

ConfigureSwagger(services);

protected virtual void ConfigureSwagger(IServiceCollection services)
        {
            // to view online help, goto ~/swagger/
            services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();

            services.AddSwaggerGen(options =>
            {
                // add a custom operation filter which sets default values
                options.OperationFilter<SwaggerDefaultValues>();
            });
            services.ConfigureSwaggerGen(options => { });
        }


 public class ConfigureSwaggerOptions : IConfigureOptions<SwaggerGenOptions>
    {
        readonly IApiVersionDescriptionProvider provider;

        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigureSwaggerOptions"/> class.
        /// </summary>
        /// <param name="provider">The <see cref="IApiVersionDescriptionProvider">provider</see> used to generate Swagger documents.</param>
        public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider) => this.provider = provider;

        /// <inheritdoc />
        public void Configure(SwaggerGenOptions options)
        {
            // add a swagger document for each discovered API version
            // note: you might choose to skip or document deprecated API versions differently
            foreach (var description in provider.ApiVersionDescriptions)
            {
                options.SwaggerDoc(description.GroupName, CreateInfoForApiVersion(description));
            }

            options.OrderActionsBy(apiDesc => apiDesc.RelativePath);

            options.IncludeXmlComments(Path.ChangeExtension(typeof(Startup).GetTypeInfo().Assembly.Location, "xml"));
            options.DescribeAllEnumsAsStrings();
            options.DescribeStringEnumsInCamelCase();

            //options.AddSecurityDefinition("oauth2",
            //    new OAuth2Scheme
            //    {
            //        Type = "oauth2",
            //        Flow = "implicit",
            //        AuthorizationUrl = new Uri("/connect/authorize", UriKind.Relative).ToString(),
            //        Scopes = new Dictionary<string, string>
            //        {
            //            {"api1", "DEMO API"}
            //        }
            //    });

            //options.AddSecurityRequirement(new[] { "oauth2", "api1" });

            options.AddSecurityDefinition("oauth2",
                new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.OAuth2,

                    Flows = new OpenApiOAuthFlows
                    {
                        Implicit = new OpenApiOAuthFlow
                        {
                            AuthorizationUrl = new Uri("/connect/authorize", UriKind.Relative),
                            Scopes = new Dictionary<string, string>
                            {
                                {Program.ResourceIdentifier, Program.ApplicationName}
                            }
                        }
                    }
                });

            options.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference
                        {
                            Type = ReferenceType.SecurityScheme,
                            Id = "oauth2"
                        }
                    },
                    new[] {"oauth2", Program.ResourceIdentifier }
                }
            });

            options.EnableAnnotations();

            //options.DocInclusionPredicate((docName, apiDesc) =>
            //{
            //    if (!apiDesc.TryGetMethodInfo(out MethodInfo methodInfo)) return false;

            //    var versions = methodInfo.DeclaringType
            //        .GetCustomAttributes(true)
            //        .OfType<ApiVersionAttribute>()
            //        .SelectMany(attr => attr.Versions);

            //    return versions.Any(v => $"v{v.ToString()}" == docName);
            //});
        }

        static OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description)
        {
            var info = new OpenApiInfo
            {
                Title = Program.ApplicationName,
                Version = $"v{description.ApiVersion}",
                Description = "A sample application with Swagger, Swashbuckle, and API versioning."

            };

            if (description.IsDeprecated)
            {
                info.Description += " This API version has been deprecated.";
            }

            return info;
        }
    }


public static void UseSwaggerMiddleware(this IApplicationBuilder app, IApiVersionDescriptionProvider provider)
        {
            app.UseSwagger();
            // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                // build a swagger endpoint for each discovered API version
                foreach (var description in provider.ApiVersionDescriptions)
                {
                    c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
                }

                //OAuth2
                c.OAuthClientId("{clientId}");
                //c.OAuth2RedirectUrl("");
                //c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
                c.OAuthClientSecret("{ClientSecret}");
                c.OAuthAppName("{AppName}");
                c.OAuthScopeSeparator("openid profile email");
                c.OAuthAdditionalQueryStringParams(new Dictionary<string, string>
                {
                    { "response_type","token"}
                });

            });
        }

enter image description here

Скрыть ошибки

Auth error
{"state":"VGh1IE9jdCAwMyAyMDE5IDE1OjI4OjEyIEdNVCsxMDAwIChBVVMgRWFzdGVybiBTdGFuZGFyZCBUaW1lKQ==","error":"unsupported_response_type","error_description":"The+response+type+is+not+supported+by+the+authorization+server.+Configured+response+types:+[id_token,+code]."}

Как настроить клиент авторизации swagger с токеном JWT.

1 Ответ

0 голосов
/ 04 октября 2019

Наконец-то найдено решение

Нужно сделать эту настройку на ядре asp.net

public static void UseSwaggerMiddleware(this IApplicationBuilder app, IApiVersionDescriptionProvider provider, IConfiguration Configuration)
        {
            app.UseSwagger();
            // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                // build a swagger endpoint for each discovered API version
                foreach (var description in provider.ApiVersionDescriptions)
                {
                    c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
                }

                //c.SwaggerEndpoint("/swagger/v2/swagger.json", "DEMO Api v2");
                //c.SwaggerEndpoint("/swagger/v1/swagger.json", "DEMO Api v1");

                //OAuth2
                var OktaConfig = new OktaConfig();
                Configuration.GetSection("OktaConfig").Bind(OktaConfig);
                c.OAuthClientId(OktaConfig.ClientId);
                c.OAuth2RedirectUrl($"{OktaConfig.RedirectUrl}/swagger/oauth2-redirect.html");
                c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
                c.OAuthClientSecret(OktaConfig.ClientSecret);
                c.OAuthAppName(OktaConfig.ClientName);
                c.OAuthScopeSeparator($"openid profile email {Program.ResourceIdentifier}");
                c.OAuthAdditionalQueryStringParams(new Dictionary<string, string>
                {
                    { "response_type","token"},
                    { "nonce", "nonce" }
                });
                //c.ConfigObject.DeepLinking = true;

            });
        }

И нужно добавить политики и правила

added swagger

...