【发布时间】:2020-10-20 21:57:56
【问题描述】:
我有以下在身份验证期间创建 JWT 令牌的方法:
private String createToken(Map<String, Object> claims,
String subject) {
JwtBuilder builder = Jwts.builder().setClaims(claims)
.setSubject(subject)
.setIssuedAt(
new Date(System.currentTimeMillis()));
builder = builder
.setExpiration(
new Date(System.currentTimeMillis() +
1000 * 60 * 60 * 10));
builder = builder
.signWith(
SignatureAlgorithm.HS256,
SECRET_KEY); //error on this line
return builder.compact();
}
但是我在builder.signWith() 行上得到了NullPointerException。
我不知道为什么。 .setExpiration() 行之后的 builder 不为空。我检查了调试器(.signWith() 行上的断点),似乎没问题:
claims 不为空,包含主题和日期:
这是完整的错误:
org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/testproject_war_exploded] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at javax.xml.bind.DatatypeConverter.parseBase64Binary(DatatypeConverter.java:296)
at io.jsonwebtoken.impl.Base64Codec.decode(Base64Codec.java:26)
at io.jsonwebtoken.impl.DefaultJwtBuilder.signWith(DefaultJwtBuilder.java:99)
at testproject.security.JwtUtil.createToken(JwtUtil.java:52)
【问题讨论】:
-
也许 SECRET_KEY 为空?
-
@Maurice 不,不是这样:查看第一张调试器图片
-
这似乎是一个奇怪的问题,我建议不要使用 builder = builder.setExpiration ,您可以从 builder 模式中受益并在一行中设置所有值。类似于下面的代码 Jwts。 builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis())) .signWith(SignatureAlgorithm.HS512, SECRET_KEY).compact ()
-
@NageshTripathi 最初给我错误的是单线;我只将它分成几行以确保
builder永远不会为空
标签: java spring spring-boot spring-mvc jwt