我在使用 JJWT 库创建 JWT 时遇到问题:https ://github.com/jwtk/jjwt
我已经按照说明提出了这个简单的课程:
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Calendar;
import java.util.Date;
public class Test {
public static void main(String[] args){
Date date = new Date();
Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, 1);
Date expirationDate = cal.getTime();
String jws = Jwts.builder()
.setSubject("user")
.setId("1")
.setIssuer("me")
.setIssuedAt(new Date())
.setExpiration(expirationDate)
.setIssuedAt(date)
.signWith(key)
.compact();
System.out.println("jws: "+ jws);
decode(jws);
}
public static Jws<Claims> decode(String token){
return Jwts.parser().setSigningKey(Keys.secretKeyFor(SignatureAlgorithm.HS256)).parseClaimsJws(token);
}
}
当我运行它时,我得到输出:
jws: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwianRpIjoiMSIsImlzcyI6InZpY3RvciIsImlhdCI6MTU3NjEwMTAyNiwiZXhwIjoxNTc2MTA0NjI2fQ.28JIsQSc273GT_qjyXEGjyh5KTJJ3thYVGQAa4ZQzvo
和例外:
Exception in thread "main" io.jsonwebtoken.security.SignatureException: JWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:383)
at io.jsonwebtoken.impl.DefaultJwtParser.parse(DefaultJwtParser.java:513)
at io.jsonwebtoken.impl.DefaultJwtParser.parseClaimsJws(DefaultJwtParser.java:573)
at Test.decode(Test.java:38)
at Test.main(Test.java:33)
此外,当我在此站点上粘贴我的 jwt 时:https ://jwt.io/ 它给了我正确的(我认为)标题:
{
"alg": "HS256"
}
和正确的有效载荷:
{
"sub": "user",
"jti": "1",
"iss": "victor",
"iat": 1576100934,
"exp": 1576104534
}
但它说签名无效。
我究竟做错了什么?如何正确创建签名?