How to handle token expiration and automatic refreshing of tokens in REST Assured?

HOME

<dependencies>
 
       <!-- Rest Assured Dependency -->
      <dependency>
         <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.4.0</version>
        <scope>test</scope>
      </dependency>

      <!-- JSON path Dependency -->
      <dependency>
         <groupId>io.rest-assured</groupId>
         <artifactId>json-path</artifactId>
         <version>5.4.0</version>
         <scope>test</scope>
      </dependency>
 
        <!-- TestNG Dependency-->
      <dependency>
          <groupId>org.testng</groupId>
         <artifactId>testng</artifactId>
         <version>7.8.0</version>
         <scope>test</scope>
       </dependency>
 
</dependencies>

import io.restassured.RestAssured;
import io.restassured.response.Response;

import java.time.Instant;

public class TokenGeneration {

    private static String accessToken;
    private static Instant tokenExpiryTime;
    Response response;
    int expiresIn;

    // Method to obtain initial token
    public static String getAccessToken() {
        if (accessToken == null || isTokenExpired()) {
            refreshAccessToken();
        }
        return accessToken;
    }

    // Method to check if the token is expired
    private static boolean isTokenExpired() {
        return tokenExpiryTime == null || Instant.now().isAfter(tokenExpiryTime);
    }

    // Method to refresh token
    private static void refreshAccessToken() {
            response = RestAssured.given()
            .contentType("application/x-www-form-urlencoded")
            .formParam("grant_type", "client_credentials")
            .formParam("client_id", "your-client-id")
            .formParam("client_secret", "your-client-secret")
            .post("https://your-auth-server.com/oauth/token");

        accessToken = response.jsonPath().getString("access_token");
        expiresIn = response.jsonPath().getInt("expires_in");
        tokenExpiryTime = Instant.now().plusSeconds(expiresIn);

        System.out.println("Access Token: " + accessToken);
        System.out.println("Token Expiry Time: " + tokenExpiryTime);
    }
}

tokenExpiryTime == null || Instant.now().isAfter(tokenExpiryTime);
tokenExpiryTime = Instant.now().plusSeconds(expiresIn);
import static io.restassured.RestAssured.given;
import org.testng.annotations.Test;

public class ApiTest {

        String token = TokenGeneration.getAccessToken();
        Response response;

       @Test
       public getResponse() {
         response = given()
                .auth().oauth2(token)
                .when()
                .get("https://example.com/protected/resource")
                .then()
                .statusCode(200)
                .extract().response();

        System.out.println("Response: " + response.asString());
    }
}

private static final long TOKEN_EXPIRY_BUFFER_SECONDS = 60;  // 1 minute buffer
    
private static boolean isTokenExpired() {
        return tokenExpiryTime == null || Instant.now().isAfter(tokenExpiryTime.minusSeconds(TOKEN_EXPIRY_BUFFER_SECONDS));
 }

Leave a comment