For the problem stated in the title, when I attempt an RSA256 Access Token, the JWT Decode decodes it and more importantly, "OnTokenValidated" gets called from the JwtBearer events. Here's the code shortened for brevity. Remember, this works fine with RSA, but NOT HS (some parts of the code were left out for brevity). Any help is a God-send as I've struggled with this for more than a few hours. Please let me know if you can help:
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;
});
}