我在 ASP.NET Core 2.2 Web API 中设置了 JWT 中间件。它仅适用于 RSA256 而不是 HS256

I have JWT middleware set up in ASP.NET Core 2.2 Web API. It only works with RSA256 and NOT HS256

对于标题中所述的问题,当我尝试使用 RSA256 访问令牌时,JWT 解码对其进行解码,更重要的是,"OnTokenValidated" 从 JwtBearer 事件中被调用。这是为简洁起见而缩短的代码。请记住,这适用于 RSA,但不适用于 HS (为简洁起见,省略了部分代码)。任何帮助都是 God-send,因为我已经为此苦苦挣扎了几个多小时。 如果你能提供帮助,请告诉我:

public void ConfigureServices(IServiceCollection services)
 {
            var tokenValidationParameters = new TokenValidationParameters
                    {
/* I understand that I need to (and I did unsuccessfully) change these for HS256) */
                        IssuerSigningKey = new RsaSecurityKey(RSA.Create(2048)),
                        ValidateIssuer = true,
                        ValidIssuer = appSettings.Auth0Issuer,
                        ValidateIssuerSigningKey = true,
                        ValidateLifetime = false,
                        RequireExpirationTime = true,
                        ValidAudience = appSettings.Auth0Audience,
                        ValidateAudience = true
                    };

            services.AddAuthentication(
                x =>
                {
                    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                }).AddJwtBearer(
                x =>
                {
                    x.Authority = appSettings.Auth0Tenant;
                    x.Events = new JwtBearerEvents
                    {
                        OnTokenValidated = context =>
                                           {
                                               string token = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", string.Empty);
                                               IDictionary<string, object> headers = AuthenticationHelper.JwtHeaders(token);

                                               // Validate the HS256 Key using a PSK
                                               if (headers.ContainsKey("alg") && headers["alg"].ToString() == "HS256")
                                               {
                                                   string secret = appSettings.Auth0MachineToMachineSecret;
                                                   string payload = AuthenticationHelper.JwtDecode(token, secret);
                                                   this.SetTokenInfo(JObject.Parse(payload), context, appSettings.Auth0AppMeta);
                                               }

                                               // Validate token with a public RSA key published by the IDP as a list of JSON Web Keys (JWK)
                                               // step 0: you've read the keys from the jwks_uri URL found in http://<IDP authority URL>/.well-known/openid-configuration endpoint
                                               if (!headers.ContainsKey("alg") || headers["alg"].ToString() != "RS256")
                                               {
                                                   context.Fail("No algorithm was present or validated");
                                                   return Task.CompletedTask;
                                               }

                                               List<IDPKey> idpKeys = AuthenticationHelper.GetIdpKeys(appSettings.Auth0Tenant);
                                               IDPKey iDpKey = AuthenticationHelper.FindIdpKey(headers, "kid", idpKeys);

                                               if (iDpKey == null)
                                               {
                                                   context.Fail($"Invalid authorization scheme: {context.Request}");
                                                   return Task.CompletedTask;
                                               }

                                               try
                                               {
                                                   //If everything is good set the Authorization as true and the CRM user.
                                                   JObject payload = AuthenticationHelper.ParsePayload(token);
                                                   this.SetTokenInfo(payload, context, appSettings.Auth1AppMeta);
                                               }
                                               catch (JoseException ex)
                                               {
                                                   context.Fail(ex);
                                               }

                                               context.Success();

                                               return Task.CompletedTask;
                                           },
                        OnAuthenticationFailed = context =>
                                                 {
                                                     return Task.FromException(context.Exception);
                                                 }
                    };
                    x.TokenValidationParameters = tokenValidationParameters;
                });
 }

他们给了我一个过期的令牌,而不是一个有效的令牌。现在 HS256 和 RSA256 都会触发 "OnTokenValidated" JwtBearer 事件。