首页 > 解决方案 > Auth0 + Swashbuckle .Net Core 2.2。使用 SwaggerUI 时 jwt 令牌中缺少声明

问题描述

我正在制作一个通过 Auth0 进行身份验证的 ASP.Net Core WebApi。我正在使用 Swagger 和 SwaggerUI 并尝试从 Swagger UI 进行身份验证。

// Add authentication services
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect("Auth0", options =>
            {
                // Set the authority to your Auth0 domain
                options.Authority = $"https://{Configuration["Auth0:Authority"]}";
                // Configure the Auth0 Client ID and Client Secret
                options.ClientId = Configuration["Auth0:ClientId"];
                options.ClientSecret = Configuration["Auth0:ClientSecret"];
                // Set response type to code
                options.ResponseType = "code";

                // Configure the scope
                options.Scope.Clear();
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("offline_access");
                options.SaveTokens = true;

                // Set the callback path, so Auth0 will call back to http://localhost:3000/callback
                // Also ensure that you have added the URL as an Allowed Callback URL in your Auth0 dashboard
                options.CallbackPath = new PathString("/callback");

                // Configure the Claims Issuer to be Auth0
                options.ClaimsIssuer = "Auth0";

                // Saves tokens to the AuthenticationProperties
                options.SaveTokens = true;

                options.Events = new OpenIdConnectEvents
                {
                    OnRedirectToIdentityProvider = context =>
                    {
                        context.ProtocolMessage.SetParameter("audience", @"https://predictor-dev.api");
                        return Task.FromResult(0);
                    },
                    // handle the logout redirection 
                    OnRedirectToIdentityProviderForSignOut = (context) =>
                    {
                        var logoutUri = $"https://{Configuration["Auth0:Authority"]}/v2/logout?client_id={Configuration["Auth0:ClientId"]}";

                        var postLogoutUri = context.Properties.RedirectUri;
                        if (!string.IsNullOrEmpty(postLogoutUri))
                        {
                            if (postLogoutUri.StartsWith("/"))
                            {
                                // transform to absolute
                                var request = context.Request;
                                postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + postLogoutUri;
                            }
                            logoutUri += $"&returnTo={ Uri.EscapeDataString(postLogoutUri)}";
                        }

                        context.Response.Redirect(logoutUri);
                        context.HandleResponse();

                        return Task.CompletedTask;
                    }
                };
            })
            .AddJwtBearer(options =>
             {
                 options.Authority = Configuration["Auth0:Authority"];
                 options.Audience = Configuration["Auth0:Audience"];
                 options.TokenValidationParameters = new TokenValidationParameters
                 {
                     RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/roles"
                 };
                 options.ClaimsIssuer = "Auth0";
             });

            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder =>
                    {
                        builder
                        .WithOrigins(Configuration["FrontendBaseUrl"])
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();
                    });
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "Predictor API", Version = "v1" });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);

                c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type = "oauth2",
                    Flow = "implicit",

                    AuthorizationUrl = $"{Configuration["Auth0:Authority"]}authorize?audience={Configuration["Auth0:Audience"]}",
                    Scopes = new Dictionary<string, string>
                    {
                        { "read:books", "Access read book operations" },
                        { "write:books", "Access write book operations" }
                    }
                });

                c.OperationFilter<SecurityRequirementsOperationFilter>();
            });

这是通过 SwaggerUI 进行身份验证后返回的令牌:

{
  "iss": "my iss",
  "sub": "my sub",
  "aud": "my aud",
  "iat": 1556002815,
  "exp": 1556010015,
  "azp": "azp",
  "scope": "read:books"
}

这里的问题是 token 没有 openid 和 profile 信息。我在 Auth0 中没有任何可以限制我的范围的自定义规则(我完全删除了它们)。我尝试了不同的选项,但我无法获得任何额外的声明。

我缺少 Swagger 中的任何配置吗?

谢谢你。

标签: asp.net-coreswaggerswagger-uiauth0swashbuckle

解决方案


您必须传递“openid”和“profile”范围以使用 openid 和配置文件信息扩展您的令牌


推荐阅读