【发布时间】:2019-04-04 12:08:36
【问题描述】:
我在我的一个应用程序中使用 JWT Authentictaion 以及 Spring Boot/Security,这是我对 JWT 的第一次尝试。
以下是我设置和获取的身份验证方法:
static void addAuthentication(HttpServletResponse res, JWTPayload payload) {
// all authentication related data like authorities and permissions can be
// embed to the token in a map using setClaims()
Map<String, Object> claims = new HashMap<String, Object>();
claims.put("roles", payload.getRoles());
claims.put("permissions", payload.getPermissions());
String JWT = Jwts.builder()
.setSubject(payload.getUsername())
.setClaims(claims)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
res.addHeader(HEADER_STRING, TOKEN_PREFIX + " " + JWT);
}
/**
* this method retrives the token from the header and validates it.
* this method is called from the JWTAuthentication filter which is
* used against all the incoming calls except the login.
* @param request
* @return
*/
static Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
if (token != null) {
// parse the token.
String user = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody()
.getSubject();
return user != null ?
new UsernamePasswordAuthenticationToken(user, null, emptyList()) :
null;
}
return null;
}
JWT 在标头中生成和接收就好了。但是,如果在后续 API 调用中使用,我会收到以下错误。
io.jsonwebtoken.ExpiredJwtException: JWT expired at 2018-10-31T16:06:05Z. Current time: 2018-10-31T16:06:08Z, a difference of 3421 milliseconds. Allowed clock skew: 0 milliseconds.
例外情况是允许的时钟偏差为 0 毫秒。在我上面的代码中,EXPIRATIONTIME 设置为 30000(我相信这是以秒为单位设置的)。我也试过增加这个值,但我仍然得到错误。
请指出我做错了什么?
【问题讨论】:
标签: authentication spring-security jwt