I need to work on a validation token for an api on my project. The api part is done and it works, but the token verification doesn't.
I follow this website proposition : https://www.baeldung.com/java-jwt-token-decode.
Here the code i'm using :
//delete the "bearer" word on my token, Also Authorization = token
String withoutBearer = Authorization.substring(7);
//split the token
String[] chunks = withoutBearer.split("\\.");
//decode each part of the splitted token
Base64.Decoder decoder = Base64.getUrlDecoder();
String header = new String(decoder.decode(chunks[0]));
String payload = new String(decoder.decode(chunks[1]));
//using RS256 Algorithm
SignatureAlgorithm sa = SignatureAlgorithm.RS256;
//secretKey = the public key i used to verify the signature
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), sa.getJcaName());
String tokenWithoutSignature = chunks[0] + "." + chunks[1];
String signature = chunks[2];
if (validator.isValid(tokenWithoutSignature, signature)){
//my api code no use here
}
using this code, i got an error asking me to use RSAPublic (or Secret) key instead of SecretKeySpec.
But when i try to use RSAPublicKey with the correct key, i got several type of error, like :
- java.security.spec.InvalidKeySpecException: Only RSAPublicKeySpec and X509EncodedKeySpec supported for RSA public keys
- java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
do you have any solution to give me please ?
or my second solution is :
/*solution 2 */
//"my key" is not the key i used, i got it from azure link and, i tried it on jwt.io, it validated
String signatureKey = "my key"
X509EncodedKeySpec spec = new X509EncodedKeySpec(signatureKey.getBytes());
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPublicKey pubkey = (RSAPublicKey) kf.generatePublic(spec);
DefaultJwtSignatureValidator validator = new DefaultJwtSignatureValidator(sa, pubkey);