Java: Timed token management class for Web API authentication

We examined the implementation of exclusive processing (Java) when sharing a timed token for Web API authentication (assuming an OAuth2 access token) among multiple threads.

Token management specifications

The specifications for token management assume the following.

Implementation code (Java)

The token management class that works with the above specifications is implemented as follows.

public class TokenManager {

	//Singleton pattern
	private static TokenManager instance = new TokenManager();
	private TokenManager() {}
	public static TokenManager getInstance() {
		return instance;
	}

    /*Token and update date and time should be volatile variables so that the latest state can always be obtained at the time of reference.*/
    //Timed token
	private volatile String token = null;
    //Update date and time (UNIX time stamp) calculated from the token validity period
   	private volatile long refreshAt = 0L;

    //Synchronized is not required because the latest state is acquired with a volatile variable.
	public String getToken() {
		if (System.currentTimeMillis() >= refreshAt) {
			syncUpdateToken();
		}
		return this.token;
	}

    //Update processing is synchronized and exclusively controlled (so that only one thread can be executed at a time)
	private synchronized void syncUpdateToken() {
        //Do not re-execute the update process in the subsequent thread that called getToken during the update process.
		if (System.currentTimeMillis() < refreshAt) {
			return;
		}

		//Token update process
        //To ensure that the latest token can be obtained when the expiration date verification is passed by the getToken method.
        // token ->Refresh in the order of refreshAt.
		this.token = ...
		this.refreshAt = ...
	}
}

By making the instance variable (token, refreshAt) a volatile variable, it is not necessary to make the token reference method (getToken) synchronized, and the reference processing within the token expiration date can be executed in parallel.

In this case, since the subsequent thread that called getToken during the update process calls the token update method (updateToken), the expiration date is verified again in the method to prevent unnecessary token update process.

Recommended Posts

Java: Timed token management class for Web API authentication
[Java] Package for management
Sample (Java) for OAuth 2.0 authentication and access token acquisition
Create API key authentication for Web API in Spring Security
[Java] Memo for naming class names
A story about Java 11 support for Web services
ChatWork4j for using the ChatWork API in Java
Docker Container Operations with Docker-Client API for Java
Generate Java client code for Salesforce SOAP API
Dreaming of easily creating a Web API for the DB of an existing Java system