我正在尝试验证jwt令牌并获取异常:线程“ main”中的异常java.lang.IllegalArgumentException:当前仅支持私钥数据
关于如何使用公共密钥验证jwt令牌的任何指针?
import org.springframework.security.jwt.JwtHelper;
public boolean verify(String jwtToken) {
ResponseEntity<JwtKey> response = restTemplate.getForEntity(tokenKey, JwtKey.class);
JwtKey jwtKey = response.getBody();
Jwt decode = JwtHelper.decode(jwtToken);
System.out.println(decode);
System.out.println(decode.getClaims());
JwtHelper.decodeAndVerify(jwtToken, new RsaVerifier(jwtKey.getValue()));
return true;
}
答案 0 :(得分:3)
最后,我采用了以下解决方案。
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.apache.commons.lang.StringUtils;
public boolean verify(String jwtToken) {
JWTKey jwtKey = restTemplateManager.getTokenPublicKey();
try {
JwtHelper.decodeAndVerify(jwtToken, new RsaVerifier(getRSAPublicKey(jwtKey.getValue())));
} catch (Exception e) {
logger.error("Error in verifying token{}", e);
return false;
}
return true;
}
private RSAPublicKey getRSAPublicKey(String publicKey) {
if( StringUtils.isBlank(publicKey)) return null;
publicKey = sanitaize(publicKey);
try {
KeyFactory keyFactory = java.security.KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(java.util.Base64.getDecoder().decode(publicKey));
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
logger.error("Error forming RSA key {}", e);
throw new GatewayException(e);
}
}
答案 1 :(得分:1)
使用公共密钥创建RsaVerifier:
@Bean RsaVerifier rsaVerifier(){
Resource resource = new ClassPathResource(pubKeyFilename);
try {
String pubKey = IOUtils.toString(resource.getInputStream(), "UTF-8");
return new RsaVerifier(pubKey);
} catch (final IOException e) {
throw new Exception("Cannot get public key to check JWT",e);
}
}
要解码时使用它:
Jwt jwt = JwtHelper.decodeAndVerify(token, rsaVerifier());