Keycapture JWT访问令牌的Java离线验证



我从Key斗篷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/:查询Keycloft

{
"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);

怎么了?我在这段代码中看到了很多例子,所以我怀疑问题出在密钥本身。

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

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

相关内容

  • 没有找到相关文章

最新更新