JWT Token is always received as expired while pars

2019-08-24 04:50发布

问题:

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 ?

回答1:

Not sure if you have already got an answer, but someone might benefit from this some time. I had the same problem initially and I thought it was an issue with JWT. But, when I debugged my code, got to know that I was doing a silly mistake and the expiration date was set in the past.

So, for testing this I have created a sample program that you can execute standalone. Check this and modify your code accordingly. Hope this helps.

import java.security.Key;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class TestJWTToken {
    private static final String API_KEY = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static void main(String... args) {
        String jwt = createJWT();
        System.out.println("JWT: " + jwt);
        parseJWT(jwt);
    }

    private static String createJWT() {
        Calendar cal = Calendar.getInstance(Locale.UK);
        Calendar cal1 = Calendar.getInstance(Locale.UK);
        cal1.setTime(cal.getTime());
        cal1.add(Calendar.SECOND, 300);

        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(API_KEY);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, SignatureAlgorithm.HS256.getJcaName());

        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        String someId = UUID.randomUUID().toString();

        return Jwts.builder().setHeader(map).setIssuer("service_provider").setSubject("consumer_provider_connectivity_token")
                .claim("some_id", someId).setIssuedAt(cal.getTime()).setExpiration(cal1.getTime())
                .signWith(SignatureAlgorithm.HS256, signingKey).compact();
    }

    private static void parseJWT(String jwt) {
        Jws<Claims> jwsClaims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(API_KEY)).parseClaimsJws(jwt);
        System.out.println("JWT decoded: " + jwsClaims);

        Claims claims = jwsClaims.getBody();
        System.out.println("Subject: " + claims.getSubject());
        System.out.println("Issuer: " + claims.getIssuer());
        System.out.println("Issued at: " + claims.getIssuedAt());
        System.out.println("Expiration: " + claims.getExpiration());
        System.out.println("Some_Id: " + claims.get("some_id"));
    }
}