'How to check if token expired in java?

I have user which have: id, username,password, tokenExpires which is Date. When i generate token i generate a string, how to check if token is not expired?



Solution 1:[1]

java.time

Do use java.time, the modern Java date and time API, for your date and time work.

public class User {
    private String username;
    private String password;
    private Instant tokenExpires;
    
    // constructor, getters, setters
    
    public boolean isTokenExpired() {
        return ! Instant.now().isBefore(tokenExpires);
    }
    
}

The modern replacement for a Date is an Instant. It’s a point in time.

If you cannot change the User class and getTokenExpires() returns an old-fashioned Date object:

    Instant tokenExpires = yourUser.getTokenExpires().toInstant();
    if (Instant.now().isBefore(tokenExpires)) {
        System.out.println("Token has not expired");
    } else {
        System.out.println("Token has expired");
    }

Link: Oracle tutorial: Date Time explaining how to use java.time.

Solution 2:[2]

The core logic behind it will be to compare the present date with the token date. If the present date is greater than the token date then the token has expired. Here is a code example of doing the same.

  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  Date date1 = sdf.parse("2009-12-31");
  Date date2 = sdf.parse("2010-01-31");

  if (date1.compareTo(date2) >= 0) 
      System.out.println("Token not expired");
  else if (date1.compareTo(date2) < 0) 
      System.out.println("Token expired");

Reference Link : How to compare dates in Java

Solution 3:[3]

Maybe it's better to use JWT. You can define how long the token should be valid and data about the user can be stored as claims. Here is example tutorial: https://developer.okta.com/blog/2018/10/31/jwts-with-java I think it's a better solution because you don't need to implement all features. On your current implementation is a chance that some user will modify the payload. But remember that data like passwords should not be included to JWT because anyone who has the token can read all claims.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Arek Szast