我刚刚发现auth0存在问题,它与auth0配置受众有关。因此,当我明确地写给读者时,JWT验证失败,并显示错误The provided Algorithm doesn't match the one defined in the JWT's Header.
。当我不写给读者时,一切都会正常进行,除非现在每次令牌过期并且用户单击登录链接时,它都会跳过登录过程并立即使用先前的凭据登录。我不希望发生这种情况,我希望用户在令牌过期后仍然能够再次进行身份验证,就像我写给读者那样。
那么观众是什么,为什么会影响这样的行为?
如何解决它以获得我想要的行为?
下面是Auth0的配置
auth0 = new auth0.WebAuth({
clientID: environment.auth0ClientId,
domain: environment.auth0Domain,
responseType: 'token id_token',
//Below is the audience I'm talking about
audience: '${constants.MY_APP}/userinfo',
redirectUri: `${constants.ORIGIN_URL}/auth`,
scope: 'openid email'
});
我需要知道如何使JWT正确验证,以及在JWT到期时如何正确进行登录。
答案 0 :(得分:0)
Auth0可以发出两种类型的令牌:不透明和JWT。
指定audience
参数时,您将收到一个JWT令牌。 JWT与不透明令牌的不同之处在于它们是独立的,因此您可以直接在应用程序中对其进行验证。
在这种情况下,您收到的JWT的签名算法与验证逻辑中定义的算法不同。您可以使用https://jwt.io对JWT进行解码,并可以在标头的alg
属性中看到使用它签名的算法。
您还可以在Auth0信息中心中找到您的API使用的签名算法。转到API,单击您的API,单击“设置”选项卡,然后滚动到“令牌设置”。您将看到它列为“签名算法”。
从错误消息来看,您正在使用java-jwt
库,在这种情况下,您需要按照此处概述的步骤相应地更改签名算法:https://github.com/auth0/java-jwt#verify-a-token
对于HS256:
try {
Algorithm algorithm = Algorithm.HMAC256("secret");
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
} catch (JWTVerificationException exception){
//Invalid signature/claims
}
secret
是您API的签名秘诀。
对于RS256,它涉及更多一点。首先,您需要解码令牌以从标头中检索kid
(密钥ID):
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE";
try {
DecodedJWT jwt = JWT.decode(token);
} catch (JWTDecodeException exception){
//Invalid token
}
然后,您需要使用jwks-rsa-java库来构造JwkProvider:
JwkProvider provider = new UrlJwkProvider("https://your-domain.auth0.com/");
Jwk jwk = provider.get(token.getKeyId());
最后,您可以使用从JWKS检索到的公钥并将其用于验证令牌:
RSAPublicKey publicKey = (RSAPublicKey) jwk.getPublicKey();
try {
Algorithm algorithm = Algorithm.RSA256(publicKey, null);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
} catch (JWTVerificationException exception) {
//Invalid signature/claims
}
请记住,出于此处概述的原因,首选使用RS256而不是HS256:https://auth0.com/docs/apis#signing-algorithms
您可能还会发现这篇文章对于验证令牌的详细信息很有用:https://auth0.com/docs/api-auth/tutorials/verify-access-token