Java从Keycloak脱机验证JWT访问令牌

时间:2020-09-24 09:06:35

标签: java validation jwt keycloak

我从Keycloak http://localhost:8080/auth/realms/MyRealm/protocol/openid-connect/token获得了签名的JWT令牌:

{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJqQThGdzdhRk1rTGhGc2......",
"expires_in": 300,
"refresh_expires_in": 1800,
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIzMWRjZTBjNS01MGU0LTQxZjMtODAxNC1kMTcyMjdk....",
"token_type": "bearer",
"not-before-policy": 0,
"session_state": "bd1728eb-ceda-43cf-a6e6-d637ba0da5e3",
"scope": "email profile"
}

因此访问令牌为:

eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJqQThGdzdhRk1rTGhGc2......

我查询http://localhost:8080/auth/realms/Myrealm/的Keycloak:

{
"realm": "MyRealm",
"public_key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuKQF8ewcJ/pDzhgzbTfFCoS1FLjZyO5z7CbmeWl.......",
"token-service": "http://localhost:8080/auth/realms/Myrealm/protocol/openid-connect",
"account-service": "http://localhost:8080/auth/realms/Myrealm/account",
"tokens-not-before": 0
}

所以公钥是:

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuKQF8ewcJ/pDzhgzbTfFCoS1FLjZyO5z7CbmeWl.......

现在我正在尝试进行如下离线验证:

import java.security.KeyFactory;
import java.security.spec.X509EncodedKeySpec;
import java.security.PublicKey;

String keyFromKeycloak = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuKQF8ewcJ/pDzhgzbTfFCoS1FLjZyO5z7CbmeWl.......";
byte[] bytes = keyFromKeycloak.getBytes();
KeyFactory factory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(bytes);
PublicKey pk = factory.generatePublic(encodedKeySpec);

但是我收到无效密钥的异常:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
    at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:239)
    at java.base/java.security.KeyFactory.generatePublic(KeyFactory.java:352)
Caused by: java.security.InvalidKeyException: invalid key format
    at java.base/sun.security.x509.X509Key.decode(X509Key.java:386)
    at java.base/sun.security.x509.X509Key.decode(X509Key.java:401)
    at java.base/sun.security.rsa.RSAPublicKeyImpl.<init>(RSAPublicKeyImpl.java:122)
    at java.base/sun.security.rsa.RSAKeyFactory.generatePublic(RSAKeyFactory.java:330)
    at java.base/sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:235)
    ... 3 more

我需要PublicKey对象以如下所示验证访问令牌:

Algorithm algorithm = Algorithm.RSA256(
    (RSAPublicKey) pk,
    null);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);

怎么了?我看到了很多带有此代码的示例,所以我怀疑问题出在密钥本身。

1 个答案:

答案 0 :(得分:1)

您的keyFromKeycloak字符串是Base64编码的DER SubjectPublicKeyInfo。您应该先对其进行解码,然后将其传递给X509EncodedKeySpec构造函数:

String keyFromKeycloak = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuKQF8ewcJ/pDzhgzbTfFCoS1FLjZyO5z7CbmeWl.......";
byte[] keyBytes = Base64.getDecoder().decode(keyFromKeycloak);
X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(keyBytes);