How to test OAuth2 in Rest Assured

  

What is OAuth?

OAuth is an open-standard authorization protocol. It allows one service (a client) to access another service (a resource server) on behalf of the user, without sharing user credentials.



















There are various OAuth flows:

  • Authorization Code Grant (for apps with user interaction)

  • Client Credentials Grant (for server-to-server, no user login)

  • Password Grant (deprecated)

  • Implicit Grant (deprecated)



Step-by-step Explanation

  1. Get the Access Token

    • Send a POST request to the token endpoint (/oauth/token)

    • Provide:

      • client_id

      • client_secret

      • grant_type=client_credentials

  2. Use the Access Token to Access the API

    • Add the AuthorizationBearer <access_token> header

    • Call the protected API


Example: Using https://reqres.in/



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();
    }
}



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

How to validate XML Schema in Rest Assured

  

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>




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!");
    }
}




Output


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!