Auth0 - 验证 JWT
Posted
技术标签:
【中文标题】Auth0 - 验证 JWT【英文标题】:Auth0 - verify JWT 【发布时间】:2020-11-07 08:28:23 【问题描述】:我正在尝试使用 Auth0 库验证从 OpenID 流返回的 JWT。 这是我的代码:
@Test
void verify()
final String token = "eyJraWQiOiJpc2FjLW9pZGMiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL2lzYWMuc3ZpbnQuaW5mb2NlcnQuaXQiLCJzdWIiOiJNMDE0MDE2OCIsImF1ZCI6IkVDT01NRVJDRSIsImV4cCI6MTU5NDkwNTc4OSwiaWF0IjoxNTk0OTA1NDg5LCJqdGkiOiJ2SmljeGNSTkQ1RkVCd3BGVzE2TWF3IiwibmJmIjoxNTk0OTA1MzY5LCJhdXRoX3RpbWUiOjE1OTQ5MDU0ODN9.EsK6lR9vHtLWAeoKvBL_ipJJqvzJMKCOKSPMUUcSK4W7MStQHQc0TlN20-2P8reCi69zQ-R2Fn2V_i-JnH8N1rz_Ar-SdX4ghI2BStOL8Z1Sl3iZZ3VV7dJBqAvrq5mZXTj7bdzbFwdDIEdSVYTrEDvJuNIOYP0e7RSQ5Hi-QA6tatW5_ir3DrSYDACNcXE1sacvdA2onIsyw1UrD1XW9nqsZSn4wWA0totQGJcA1FYjQb0-28Ttkt2P_5uYaX_VDojKQVfhUTJZQKGeKjBpRCVmV__I1U-nVhSnP5UcgCnjbJkO72aIGLWj7I0lLJF2gSmicfqmrAlu8MHMokAmxw";
final String publicKey = "??"
try
byte[] publicBytes = Base64.decodeBase64(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pubKey = keyFactory.generatePublic(keySpec);
final Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) pubKey, null);
final JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("https://isac.svint.infocert.it")
.build(); //Reusable verifier instance
final DecodedJWT jwt = verifier.verify(token);
logger.info("", jwt);
catch (JWTVerificationException | NoSuchAlgorithmException | InvalidKeySpecException exception)
//Invalid signature/claims
Assertions.fail(exception.getMessage());
现在,我不确定获取公钥的正确程序。 遵循 OpenID / Oauth2 协议,身份提供者公开此 API:
endporint/keys
"keys": [
"kty": "RSA",
"kid": "myidp-oidc",
"use": "sig",
"alg": "RS256",
"n": "<some_value>",
"e": "AQAB"
]
如何使用上述信息获取密钥并验证 JWT?
【问题讨论】:
【参考方案1】:已解决,我必须在 pom.xml 上导入
<dependency>
<groupId>com.auth0</groupId>
<artifactId>jwks-rsa</artifactId>
<version>0.9.0</version>
<scope>test</scope>
</dependency>
然后:
final String token = "<some_token>";
try
final DecodedJWT decodedJWT = JWT.decode(token);
final JwkProvider provider = new UrlJwkProvider(new URL("<endpoint_idp>/keys"));
final Jwk jwk = provider.get(decodedJWT.getKeyId());
final Algorithm algorithm = Algorithm.RSA256((RSAPublicKey) jwk.getPublicKey(), null);
final JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("<issue>")
.build(); //Reusable verifier instance
final DecodedJWT verifiedJWT = verifier.verify(token);
logger.info("", verifiedJWT);
catch (JWTVerificationException | JwkException | MalformedURLException exception)
//Invalid signature/claims
Assertions.fail(exception.getMessage());
【讨论】:
以上是关于Auth0 - 验证 JWT的主要内容,如果未能解决你的问题,请参考以下文章