I am using JWT in my application for login authentication process. To generate the token I am using:
Jwts.builder().setSubject(username).signWith(SignatureAlgorithm.HS512, MacProvider.generateKey()).compact();
Generated Token:
eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJlaG91c2VAZGV2ZXJldXgub3JnIn0.5SX-aU-p_RlfC3CZa-YXnQu_YR7RsG2Xfim3LOmlqxjAZrIyZiz0fYZwViHr113ms8TNvngcJcV07U4hK-RBZQ
When I decode this token in jwt.io debugger it tells me an invalid Signature. I am not able to find the reason of this failure as I can see the username in the payload which i am using to authenticate. Could anybody point me the issue? Do I need to change anything in the code?
MacProvider.generateKey()
is generating a new random signing you key each time you use it. You need to generate it once and store it. The key is used to sign and verify the token.
If you do not store the key you wil not be able to verify the token, which is exactly the problem with jwt.io. You must provide the signing key. In your case, using a random key that can contain non representble characters (it is possible to use a passphrase too, but not recommended), encode it to base64. Then mark the check in jwt.io to verify the token
Key key =MacProvider.generateKey();
String keyB64 = javax.xml.DataTypeConverter.printBase64Binary(key.getEncoded());