Skip to content

Commit

Permalink
Improve the way how we check the OIDC Access Token Expiration and Val…
Browse files Browse the repository at this point in the history
…idity By incorporating a clock skew allowance and optimizing the time comparison, you improve the reliability of your token expiration checks
  • Loading branch information
afabiani committed Nov 21, 2024
1 parent b3da4c3 commit 2f3f30d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,12 @@ public abstract class OAuth2SessionServiceDelegate implements SessionServiceDele

private static final Logger LOGGER = LogManager.getLogger(OAuth2SessionServiceDelegate.class);

private static final long CLOCK_SKEW_ALLOWANCE_MILLIS = 5 * 60 * 1000; // 5 minutes

protected UserService userService;

/**
* @param restSessionService the session service to which register this delegate.
* @param restSessionService the session service to which register this delegate?
* @param delegateName this delegate name eg. google or GitHub etc...
*/
public OAuth2SessionServiceDelegate(
Expand Down Expand Up @@ -185,8 +187,10 @@ private boolean isTokenExpired(OAuth2AccessToken token) {
}
}

// Allow clock skew if necessary
return expiration.before(new Date());
long now = System.currentTimeMillis();
long adjustedExpirationTime = expiration.getTime() + CLOCK_SKEW_ALLOWANCE_MILLIS;

return adjustedExpirationTime <= now;
}

private Date getExpirationDateFromToken(String token) {
Expand All @@ -210,9 +214,8 @@ private Date getExpirationDateFromToken(String token) {
throw new IllegalArgumentException("Cannot parse 'exp' claim from token");
}

// The 'exp' claim is usually in seconds since epoch
Date expiration = new Date(expLong * 1000);
return expiration;
// The 'exp' claim has usually been in seconds since the epoch
return new Date(expLong * 1000);
} else {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,9 @@ void testRefreshWithExpiredTokenAndUnsuccessfulRefresh() {

// Set the current access token to be expired
mockOAuth2AccessToken.setExpiration(
new Date(System.currentTimeMillis() - 1000)); // Set expiration in the past
new Date(
System.currentTimeMillis()
- 5 * 60 * 1000)); // Set expiration in the past (5 minutes)
serviceDelegate.currentAccessToken = mockOAuth2AccessToken;

// Mock the RestTemplate exchange method to simulate failure in all attempts to refresh the
Expand Down

0 comments on commit 2f3f30d

Please sign in to comment.