How to Test Token based Authentication in API by Playwright

 

To test token-based authentication in an API using Playwright in Java, you typically perform the following steps:


Workflow Explanation

  1. Get the Authentication Token
    Send a POST (or appropriate) request to the authentication endpoint with credentials to get a token.

  2. Use the Token in Headers
    For subsequent API calls, include the token in the Authorization header as a Bearer token.

  3. Validate Response
    Use assertions to verify the status code and content of the protected endpoint's response.




Example Scenario

Let’s take an example of https://reqres.in/api/login which gives a token on successful login, and then use that token to call another API like https://reqres.in/api/users




Maven Dependencies


<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.44.0</version> <!-- Use latest -->
</dependency>





Java Code: Token-based API Testing Using Playwright


import com.microsoft.playwright.*;
import com.microsoft.playwright.options.*;

import java.util.*;

public class TokenBasedAuthTest {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            APIRequest request = playwright.request().newContext();

            // Step 1: Login to get the token
            APIResponse loginResponse = request.post("https://reqres.in/api/login", 
                RequestOptions.create()
                    .setHeader("Content-Type", "application/json")
                    .setData("{ \"email\": \"eve.holt@reqres.in\", \"password\": \"cityslicka\" }")
            );

            if (loginResponse.status() != 200) {
                System.out.println("Login failed! Status: " + loginResponse.status());
                return;
            }

            // Extract token from response JSON
            String token = loginResponse.json().get("token").toString();
            System.out.println("Token received: " + token);

            // Step 2: Use token in Authorization header to call protected resource
            APIResponse userResponse = request.get("https://reqres.in/api/users/2", 
                RequestOptions.create()
                    .setHeader("Authorization", "Bearer " + token)
            );

            System.out.println("User API Status Code: " + userResponse.status());
            System.out.println("User API Response: " + userResponse.text());

            if (userResponse.status() == 200) {
                System.out.println("Token-based API access successful.");
            } else {
                System.out.println("Access failed.");
            }
        }
    }
}




Explanation

  • playwright.request().newContext() → Creates a new API context.

  • loginResponse.json().get("token") → Extracts token from login response.

  • "Authorization": "Bearer " + token → Adds the token to the headers for authentication.

No comments:

Post a Comment