对于标题中所述的问题,当我尝试使用 RSA256 访问令牌时,JWT 解码会对其进行解码,更重要的是,从 JwtBearer 事件中调用“OnTokenValidated”。为简洁起见,这是缩短的代码。请记住,这适用于 RSA,但不适用于 HS (为简洁起见,省略了部分代码)。任何帮助都是天赐之物,因为我已经为此苦苦挣扎了几个小时。如果您能提供帮助,请告诉我:
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;
});
}