带有Okta配置JWT令牌的Swagger授权

问题描述 投票:0回答:1

我正在尝试使用ASP.NET core 2.2授权带有okta配置的swagger api。

遵循了此链接中的说明https://app.swaggerhub.com/help/enterprise/user-management/sso/okta

但是我不确定该怎么做。

Okta链接

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]."}

如何使用带有JWT令牌的授权授权客户端进行配置。

asp.net asp.net-core single-page-application okta okta-api
1个回答
0
投票

终于找到了解决方法

需要在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

© www.soinside.com 2019 - 2024. All rights reserved.