Kastriot Beha
Kastriot Beha

Reputation: 9

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?

Upvotes: 0

Views: 14066

Answers (3)

Anonymous
Anonymous

Reputation: 86359

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.

Upvotes: 2

Arek Szast
Arek Szast

Reputation: 203

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.

Upvotes: 0

aesher9o1
aesher9o1

Reputation: 45

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

Upvotes: 0

Related Questions