com.nimbusds:nimbus-jose-jwt:9.13
我实现了一个休息授权服务器,它使用包以 JWK 格式返回给定 keyId 的公钥。代码看起来像这样:
@RequestMapping(value = "/oauth2", produces = APPLICATION_JSON_VALUE)
public interface Rest {
...
@GetMapping("/public-key/{keyId}")
@Operation(summary = "Return the public key corresponding to the key id")
JWK getPublicKey(@PathVariable String keyId);
}
public class RestController implements Rest {
.....
public JWK getPublicKey(String keyId) {
byte[] publicKeyBytes = ....
RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyBytes));
JWK jwk = new RSAKey.Builder(publicKey)
.keyID(keyId)
.algorithm(new Algorithm(publicKey.getAlgorithm()))
.keyUse(KeyUse.SIGNATURE)
.build();
return jwk;
}
}
此代码以以下格式返回 JWK 密钥:
{
"keyStore": null,
"private": false,
"publicExponent": {},
"modulus": {},
"firstPrimeFactor": null,
"secondPrimeFactor": null,
"firstFactorCRTExponent": null,
"secondFactorCRTExponent": null,
"firstCRTCoefficient": null,
"otherPrimes": [],
"requiredParams": {
"e": "some-valid-exponent",
"kty": "RSA",
"n": "some-valid-modulus"
},
"privateExponent": null,
"x509CertChain": null,
"algorithm": {
"name": "RSA",
"requirement": null
},
"keyOperations": null,
"keyID": "some-valid-key-id",
"x509CertURL": null,
"x509CertThumbprint": null,
"x509CertSHA256Thumbprint": null,
"parsedX509CertChain": null,
"keyUse": {
"value": "sig"
},
"keyType": {
"value": "RSA",
"requirement": "REQUIRED"
}
}
在客户端(java)上,我尝试使用以下代码解析 jwk:
public JWK getPublicKey(String keyId) {
String json = restTemplate.getForObject(publicUrl + "/oauth2/public-key/" + keyId, String.class);
try {
return JWK.parse(json);
} catch (ParseException e) {
log.error("Unable to parse JWK", e);
return null;
}
}
parse
但是,由于抛出异常 ( Missing parameter "kty"
) ,客户端无法解析密钥。我看到这JWK.parse
需要kty
主 JWT josn 主体中的密钥,而默认序列化将密钥JWK
嵌入密钥中。当我尝试时,我确实看到了json 主体中的密钥。kty
requiredParams
jwk.toString()
kty
为什么本机 JWK 对象的序列化/反序列化不能以直接的方式工作?在不实现自定义 jwt 结构或序列化器/反序列化器的情况下解决此问题的最佳方法是什么?
更新 1:如果我们将返回类型从 更改JWK
为Map<String, Object>
orString
并在客户端处理反序列化,此代码将起作用。但是,如果包本身为我们执行(反)序列化会更好。