In API testing, passing an authorization token in the header is a common requirement, especially for securing APIs with OAuth, JWT, or similar mechanisms. Rest Assured, a popular Java library for API automation, provides a simple way to handle headers, including authorization tokens.
In this blog post, I’ll walk you through the process of passing an authorization token in the header using Rest Assured.
What is an Authorization Token?
An authorization token is a piece of data that proves the identity of the user or system making the request. It is typically passed in the header of an HTTP request to validate access to secure endpoints.
The most common types of tokens are:
- Bearer Token (JWT - JSON Web Token)
- OAuth Tokens
- API Keys
Steps to Pass Authorization Token in Rest Assured
Step 1: Add Rest Assured Dependency to Your Project
Ensure your project has the Rest Assured library. If you're using Maven, include the following dependency in your pom.xml
:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.0</version> <!-- Use the latest version -->
<scope>test</scope>
</dependency>
Step 2: Generate or Obtain the Token
Tokens are typically obtained from an authentication endpoint. For this example, let’s assume you already have a token string. If you need to generate it programmatically, you can use a POST request to authenticate.
Response response = RestAssured.given()
.header("Content-Type", "application/json")
.body("{ \"username\": \"yourUsername\", \"password\": \"yourPassword\" }")
.post("https://example.com/auth/login");
String token = response.jsonPath().getString("token");
Here, the token is extracted from the response of the login endpoint.
Step 3: Use the Token in the Header
Once you have the token, pass it as a header in subsequent API requests. Use the header
or auth
method provided by Rest Assured.
Example: Passing Bearer Token
Explanation:
- The
Authorization
header contains the token in the format:Bearer <token>
. Content-Type
is set toapplication/json
to indicate that the request body is JSON (if applicable).
Step 4: Use Common Setup for Multiple Requests
If you're sending the token with multiple requests, configure it globally in Rest Assured using a RequestSpecification
.
import io.restassured.RestAssured;
import io.restassured.specification.RequestSpecification;
public class RestAssuredConfig {
public static void main(String[] args) {
String token = "your_token_here";
RequestSpecification requestSpec = RestAssured.given()
.header("Authorization", "Bearer " + token)
.header("Content-Type", "application/json");
// Use requestSpec for multiple requests
Response response1 = requestSpec.get("https://example.com/secure-endpoint1");
Response response2 = requestSpec.get("https://example.com/secure-endpoint2");
System.out.println("Response 1: " + response1.getBody().asString());
System.out.println("Response 2: " + response2.getBody().asString());
}
}
This approach avoids repetitive code and ensures consistency across requests.
Debugging and Logging Requests
Rest Assured provides excellent debugging capabilities. Use the log()
method to inspect your requests and responses.
RestAssured.given()
.header("Authorization", "Bearer " + token)
.log().all() // Logs the entire request
.get("https://example.com/secure-endpoint")
.then()
.log().all(); // Logs the entire response
Best Practices
- Secure the Token: Avoid hardcoding tokens in your code. Use environment variables or secure vaults.
- Token Expiry Handling: Implement logic to refresh tokens automatically if they expire.
- Global Configuration: Use a
RequestSpecification
for reusability. - Error Handling: Validate the response status code and handle errors gracefully.