JWT Token Invalid Signature [duplicate]

寵の児 提交于 2019-12-07 01:50:53

问题


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?


回答1:


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());


来源:https://stackoverflow.com/questions/46570389/jwt-token-invalid-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!