How to test OAuth2 in Rest Assured

  



What is OAuth2?

  • OAuth2 (Open Authorization 2.0) is an authorization framework, not an authentication protocol.
  • It allows third-party applications (clients) to gain limited access to resources (like APIs or user data) on behalf of the resource owner (the user).
  • Instead of sharing user credentials (like username/password), OAuth2 uses access tokens issued by an authorization server to access protected resources from a resource server.

Key Components in OAuth2
  • Resource Owner → The user who owns the data.
  • Client → The application requesting access on behalf of the user.
  • Authorization Server → Issues access tokens after validating the client and resource owner.
  • Resource Server → Hosts protected resources and validates access tokens before granting access.

Common OAuth2 Grant Types
  • Authorization Code Grant → Used in web and mobile apps.
  • Client Credentials Grant → For machine-to-machine communication.
  • Password Grant → Uses user credentials directly (less secure).
  • Implicit Grant → For single-page apps (not widely used now).
  • Refresh Token → To get a new access token without re-authenticating.

How to Test OAuth2 in Rest Assured

When you need to test APIs protected by OAuth2 using Rest Assured, the flow is generally:

1. Obtain an Access Token
  • Send a request to the Authorization Server’s token endpoint (e.g., /oauth/token) with required details (client ID, client secret, grant type, username, password, or authorization code depending on the flow).
  • The response will contain an access token (and sometimes a refresh token).
2. Use the Access Token in API Requests
  • For subsequent API calls to the Resource Server, include the access token in the Authorization header as:  Authorization: Bearer <access_token>
3. Validate API Responses
  • Once the token is included, the API should return data for valid tokens.
  • If the token is expired or invalid, the API should return an error (like 401 Unauthorized or 403 Forbidden).
4. Test Token Expiry & Refresh
  • Test how the system behaves when an expired token is used.
  • Test the refresh token endpoint to get a new valid access token.
5. Negative Testing
  • Try calling the API without a token → should return unauthorized.
  • Try calling the API with an invalid/expired token → should return unauthorized.
  • Try with incorrect client credentials → should be rejected at token request stage.
























Java Code using Rest Assured

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

import java.util.HashMap;
import java.util.Map;

public class OAuth2Test {

    public static void main(String[] args) {

        // Step 1: Get OAuth2 token
        String tokenUrl = "https://example.com/oauth/token"; // Replace with real token URL
       
        Map<String, String> params = new HashMap<>();
        params.put("grant_type", "client_credentials");
        params.put("client_id", "your-client-id");
        params.put("client_secret", "your-client-secret");

        Response tokenResponse = RestAssured
                .given()
                    .contentType(ContentType.URLENC)
                    .formParams(params)
                .when()
                    .post(tokenUrl)
                .then()
                    .statusCode(200)
                    .extract()
                    .response();

        String accessToken = tokenResponse.jsonPath().getString("access_token");
        System.out.println("Access Token: " + accessToken);

        // Step 2: Use token to access protected API
        String protectedUrl = "https://reqres.in/api/users?page=2";

        RestAssured
                .given()
                    .auth()
                    .oauth2(accessToken) // Add Bearer token
                .when()
                    .get(protectedUrl)
                .then()
                    .statusCode(200)
                    .log().body();
    }
}



Code explanation:

(a) Get Oauth2 token from any token provider website, we have taken dummy website as: https://example.com/oauth/token
(b) Create a map object and put values of parameters like grant type, client id and client secret.
(c) Get response from token object and print the access token by key: access_token (in your case it can be different, depends upon the key of access token response.
(d) Send request to API needs to access: https://reqres.in/api/users?page=2 and put oauth2 code as:
 .auth().oauth2(accessToken)


Important Points:

  • auth().oauth2(token) adds the Authorization: Bearer <token> header.
  • For token endpoint, many real APIs use URLs like:
https://api.example.com/oauth2/token


Suggested Posts:

1. Validate XML Schema in RestAssured
2. Validate JSON Schema in RestAssured
3. Test PUT API in RestAssured
4. Validate Response by Matchers API in RestAssured
5. Validate API Response from Database in RestAssured

How to validate XML Schema in Rest Assured

  



What is XML Schema?

  • XML Schema Definition (XSD) is a way to define the structure, rules, and constraints of an XML document.
  • It ensures that an XML file follows a predefined format.

With XSD, you can define:
  • What elements and attributes can appear in the XML.
  • The order of elements.
  • Data types of values (e.g., string, integer, date).
  • Constraints like minimum/maximum occurrence of elements.

Why validate XML Schema in API Testing?
  • To make sure the API response is structurally correct.
  • To check if all mandatory tags exist and follow the schema rules.
  • To avoid unexpected errors when consuming the API in client applications.

How to Validate XML Schema in Rest Assured

1. Prepare the Schema File (XSD)
  • Have the XSD file ready which defines the expected XML structure.
  • This file acts as the reference for validation.

2. Send Request to API
  • Use Rest Assured to send the API request (GET/POST/etc.) to get the XML response.

3. Perform Schema Validation
  • Rest Assured provides built-in XML Schema Validator support.
  • You point Rest Assured to the XSD file.
  • Rest Assured then checks the actual XML response against the XSD schema.

4. Pass/Fail Validation
  • If the response XML matches the schema → test passes.
  • If there are mismatches (missing elements, wrong data types, invalid structure) → test fails.

Steps to Validate XML using XSD in Rest Assured

  • Use a GET API that returns XML.
  • Download or write a corresponding .xsd file to validate the structure.
  • Use RestAssured and XmlValidator from io.restassured.module.jsv package.
  • Assert that the XML response conforms to the schema.













Maven Dependency:

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

    <!-- XML Path -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>xml-path</artifactId>
        <version>5.4.0</version>
    </dependency>

    <!-- XML Schema Validator -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>json-schema-validator</artifactId>
        <version>5.4.0</version>
    </dependency>
</dependencies>


You can visit: https://www.w3.org/2001/XMLSchema to know more about xml schemas

Sample XML XSD File (example.xsd)

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="note">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="to" type="xs:string"/>
        <xs:element name="from" type="xs:string"/>
        <xs:element name="heading" type="xs:string"/>
        <xs:element name="body" type="xs:string"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>


API URL that returns XML

Example: https://www.w3schools.com/xml/note.xml









(It returns XML like below)

<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>




Java Code (Using Rest Assured)

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

import java.io.File;

import static io.restassured.module.jsv.XmlSchemaValidator.matchesXsd;
import static org.hamcrest.MatcherAssert.assertThat;

public class XMLSchemaValidationTest {

    public static void main(String[] args) {
        // Set Base URI
        RestAssured.baseURI = "https://www.w3schools.com";

        // Make GET request
        Response response = RestAssured
                .given()
                .when()
                .get("/xml/note.xml")
                .then()
                .extract().response();

        // Print response (optional)
        System.out.println("Response XML:\n" + response.asString());

        // Validate response XML against XSD
        File schema = new File("src/test/resources/example.xsd"); // adjust path

        assertThat(response.asString(), matchesXsd(schema));
        System.out.println("XML Schema Validation Passed!");
    }
}



Code explanation:

(a) Set the base URI
(b) Create GET request for API: https://www.w3schools.com/xml/note.xml
(c) Print the response
(d) Validate response against XSD file: src/test/resources/example.xsd
(e)  Assert the response


Output

Below is the output of the given GET API in xml form

Response XML:
<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>
XML Schema Validation Passed!


Suggested Posts:

1. Test OAuth2 in RestAssured
2. Test Form Authentication in RestAssured
3. Test PUT API in RestAssured
4. Validate Response by Matchers API in RestAssured
5. Validate API Response from Database in RestAssured