Auth0 + Swashbuckle .Net Core 2.2。使用 SwaggerUI 时 jwt 令牌中缺少声明

Posted

技术标签:

【中文标题】Auth0 + Swashbuckle .Net Core 2.2。使用 SwaggerUI 时 jwt 令牌中缺少声明【英文标题】:Auth0 + Swashbuckle .Net Core 2.2. Missing claims in jwt token when using SwaggerUI 【发布时间】:2019-09-12 07:55:26 【问题描述】:

我正在制作一个通过 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 中是否有我遗漏的配置?

谢谢。

【问题讨论】:

【参考方案1】:

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

【讨论】:

以上是关于Auth0 + Swashbuckle .Net Core 2.2。使用 SwaggerUI 时 jwt 令牌中缺少声明的主要内容,如果未能解决你的问题,请参考以下文章

asp.net core使用Swashbuckle.AspNetCore(swagger)生成接口文档

Swashbuckle .NET Core 2 中 JWT 承载的授权

.Net Core 2.0 中的 SwashBuckle UI 显示错误

如何在 .NET Core 中实现处理自定义属性的 Swashbuckle IOperationFilter

ASP.NET Web Api 中的 Swashbuckle 被嵌套控制器混淆

2021-06-20 .NET高级班 57-ASP.NET Core Swagger的使用(Swashbuckle工具版)