简体   繁体   中英

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?

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 not expired");
    }

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM