How to Test Token based Authentication in API by Playwright




What is Token-based Authentication?

Token-based authentication is a method used to verify the identity of a user or system trying to access a protected resource (like an API or web application). Instead of repeatedly sending a username and password, the system issues a token (a unique string, often in the form of a JWT – JSON Web Token) after a successful login.


How it generally works:

  • Login: The user sends their credentials (username & password) to the authentication server.
  • Token Issuance: If valid, the server generates a token and sends it back to the client.
  • Token Usage: The client includes this token in the Authorization header (usually as Bearer <token>) for all subsequent requests.
  • Validation: The server validates the token and grants or denies access to protected resources.
  • Expiry & Refresh: Tokens often expire after some time, so refresh tokens may be used to obtain a new one without re-login.


How to Handle Token-based Authentication in Playwright Java

When automating scenarios with Playwright, token handling is key to bypass login screens or test APIs securely. Here’s how it is conceptually managed:


(1) Obtain Token Programmatically or Manually:
  • You can call the authentication API endpoint (using Java HTTP client or Playwright’s request context) with credentials and capture the token.
  • Alternatively, use a pre-generated token provided by the developer or QA team.
(2) Store Token in Test Context:
  • Keep the token in a variable or configuration file so it can be reused across requests and sessions.
(3) Attach Token to Requests:
  • Use Playwright’s APIRequestContext in Java to send API requests with headers that include the token (Authorization: Bearer <token>).
  • For browser-based flows, inject the token into browser storage:
       LocalStorage/SessionStorage: Save the token where the application expects it.
       Cookies: If the app stores the token in cookies, set them before navigating.

(4) Re-use Authenticated State:
  • Once the browser is authenticated with the token, Playwright allows saving that state (cookies, local storage).
  • This state can then be reused in subsequent tests to skip login repeatedly.
(5) Token Expiry Handling:
  • If the token expires, the automation should either:
        Request a new token before test execution, or
        Use a refresh token flow if supported.


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











Workflow Explanation

  • Get the Authentication Token
    Send a POST (or appropriate) request to the authentication endpoint with credentials to get a token.
  • Use the Token in Headers
    For subsequent API calls, include the token in the Authorization header as a Bearer token.
  • 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

https://reqres.in/api/login
















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



Code Steps:

(a) Login to get the token
(b) Extract token from response JSON
(c) Use token in Authorization header to call protected resource


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.


Suggested Posts:

1. Automate GET API in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Cookie Based Authentication in Playwright
5. Basic Authentication in Playwright