Last Updated On
Handling token expiration and automatically refreshing tokens in REST Assured involves a few steps to ensure your tests can obtain a fresh token when the current one expires.
Add the below-mentioned dependencies to the Maven project.
<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>
Implementation Steps
- Obtain Initial Access Token:– Implement a method to obtain the initial access token from the authentication server.
- Store Token and Expiration Time:- Use a structure to store the access token and its expiration time.
- Check Token Validity:– Before making an API request, check if the token is still valid. If it’s expired or about to expire, refresh it.
- Refresh the Token:- Implement a method to refresh the token.
- Update Token Storage:– Store the new token and update the expiration time after refreshing.
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);
}
}
Instant.now – The now() method of Instant returns the current time from the system clock. If the current time is “2023-10-01T12:00:00Z”, “Instant.now()“ would represent this moment in time.
isAfter(tokenExpiryTime) – checks if the current time is after the token’s expiration time.
tokenExpiryTime == null || Instant.now().isAfter(tokenExpiryTime);
plusSeconds(expiresIn) – This method adds a specified number of seconds to the Instant object. If expiresIn is “3600“ seconds (which is equivalent to 1 hour), it adds an hour to the current Instant.
tokenExpiryTime = Instant.now().plusSeconds(expiresIn);
Use the Token in REST Assured Requests.
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());
}
}
Best Practices:
Token Expiry Buffer:– Consider implementing a buffer time before the actual expiry to refresh the token. This prevents the edge cases where the token might expire during an API call.
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));
}
Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!