I am using JWT Authentictaion in one of my application along with Spring Boot/Security and its my first take on JWT.
Following are my set and get authentication methods:
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;
}
The JWT is generated and received in headers just fine. However, if used in subsequent API call, I receive following error.
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.
The exception says allowed clock skew is 0 milliseconds. In my above code EXPIRATIONTIME
is set to 30000 (I believe this is set in seconds). I have tried increasing this value too but I still get the error.
Please suggest what am I doing wrong ?