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?
For Invalid JWT Signature, check if your service account key has expired. Go to your APIs & Services to add a new key if it has.
The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way. To create the signature, the Base64-encoded header and payload are taken, along with a secret, and signed with the algorithm specified in the header.
In general, JWT is actually replacing the combination of username and password. What it means, instead of keep sending username and password for each request for a restricted resources, the server will return a unique token after verifying the the credentials is correct on the first time the user login.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With