I have created a JWT object with some data. Then I decode that same JWT object just to compare and see if the validation passes. But it does not. Following is the code I have created. What could be the issue?
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
//Make a JWT Token String
String jws = Jwts.builder().setSubject("adam")
.setExpiration(new java.util.GregorianCalendar(2021,
Calendar.NOVEMBER, 8).getTime())
.setIssuer("someUser@mycompany.com")
.claim("groups", new String[] { "user", "admin" })
// HMAC using SHA-512 and 12345678 base64 encoded
.signWith(signatureAlgorithm, "MTIzNDU2Nzg=").compact();
System.out.println("JWTS String: "+ jws.toString());
//=================================================
//Decode the string back
Base64.Decoder decoder = Base64.getDecoder();
String[] chunks = jws.split("\\.");
String header = new String(decoder.decode(chunks[0]));
String payload = new String(decoder.decode(chunks[1]));
String signature = chunks[2];
System.out.println("Header: " + header);
System.out.println("PayLoad: " + payload);
System.out.println("Signature: " + signature);
String tokenWithoutSignature = chunks[0] + "." + chunks[1];
SecretKeySpec secretKeySpec = new
SecretKeySpec("MTIzNDU2Nzg=".getBytes(),signatureAlgorithm.getJcaName());
DefaultJwtSignatureValidator validator = new
DefaultJwtSignatureValidator(signatureAlgorithm,secretKeySpec);
if (validator.isValid(tokenWithoutSignature, signature)){
System.out.println("TOKEN IS VALID");
}else{
System.out.println("TOKEN IS INVALID");
}