JWT signature does not match locally computed signature
I have had the same problem, I noticed that in sources whenever they convert the signing key they explicitly specify UTF-8 encoding. I tried changing the encoding while both decoding the token:
private Jws<Claims> decodeToken(String token) {
return Jwts.parser()
.setSigningKey(securityProperties.getTokenSecret().getBytes(Charset.forName("UTF-8")))
.parseClaimsJws(token);
}
And when signing the token:
private String getSignedToken(UserDetailsAdapter user, List<String> roles, byte[] signingKey) {
return Jwts.builder()
.signWith(Keys.hmacShaKeyFor(signingKey), SignatureAlgorithm.HS512)
.setHeaderParam("typ", securityProperties.getTokenType())
.setIssuer(guiServerSecurityProperties.getTokenIssuer())
.setAudience(guiServerSecurityProperties.getTokenAudience())
.setSubject(user.getUsername())
.setExpiration(new Date(System.currentTimeMillis() + 864000000))
.claim("rol", roles)
.compact();
}
This is the only thing that fixed this for me.
I had a similar problem. In my case it was wrong token validation. I set sign as bytes:
.signWith(SignatureAlgorithm.HS512, jwtConfig.getSecret().getBytes())
But when i was parsing the token and setting signKey i setted it as a String, not as bytes:
Jwts.parser().setSigningKey(signingKey).parseClaimsJws(this.token)
Also always check quotes and spaces when checking token, there often can be excess space/quote in the start/end of the token (use trim() method)
static Key secret = MacProvider.generateKey();
will generate a new random key each time your server is reloaded because static variables are initialized when the class is loaded
It means that if you issue a JWT, it is only valid as long as the server does not reboot. The SignatureException
you got is because the signing key it is different
You need to store the signing key secret.getEncoded()
after first generation and load it when your module starts
I had a similar problem. In my case both keys were the same, but for some reason I was receiving a token within quotes (e.g "Syasda.da3das.aDjty6"
instead of just Syasda.da3das.aDjty6
).
It took me quite some time to realize this since most of the time while testing on jwt.io I would just copy the token manually without the brackets to verify it.
token = token.replace("\"","");
Removing those quotes solved the problem for me. Hopefully this will help someone else as well.