How to Test Token based Authentication in API by Playwright

















What Is Token-Based Authentication? Complete Guide to Handling Token Authentication in Playwright Java

In today’s modern web applications and APIs, security is not optional—it is essential. One of the most widely used and secure authentication mechanisms is Token-Based Authentication. Whether you are building applications, consuming APIs, or performing automation testing, understanding how token authentication works is crucial.

If you are using Playwright with Java for API or UI automation, learning how to handle token-based authentication will allow you to bypass login screens, test secured endpoints, and build scalable automation frameworks.

In this detailed, SEO-optimized, and AdSense-friendly guide, you will learn:

  • What token-based authentication is

  • How JWT (JSON Web Token) works

  • Complete authentication workflow

  • How to handle token-based authentication in Playwright Java

  • Step-by-step API testing example

  • How to reuse authenticated state

  • How to manage token expiry

  • Best practices for secure automation

This guide is written in a natural, human-friendly tone and is perfect for beginners and experienced testers alike.


What Is Token-Based Authentication?

Token-based authentication is a secure method used to verify the identity of a user or system trying to access a protected resource such as:

  • REST APIs

  • Web applications

  • Microservices

  • Mobile backends

Instead of sending a username and password repeatedly with every request, the server issues a token after successful login.

This token acts as a temporary access key.

The most common token format used today is:

  • JWT (JSON Web Token)

A JWT is a secure, digitally signed string that contains user information and expiration details.


Why Token-Based Authentication Is Preferred Over Basic Authentication

Unlike Basic Authentication, where credentials are sent with every request, token-based authentication:

  • Reduces exposure of credentials

  • Improves scalability

  • Works well with stateless APIs

  • Supports expiration and refresh mechanisms

  • Integrates easily with modern frontend frameworks

Because of these benefits, most modern systems use token authentication instead of traditional username-password validation per request.


How Token-Based Authentication Works (Step-by-Step)

Let’s break down the typical workflow.


Step 1: User Login

The user sends credentials (email & password) to an authentication endpoint.

Example:

POST /api/login

Request body:

{ "email": "user@example.com", "password": "password123" }


Step 2: Token Issuance

If credentials are valid:

  • The server generates a token (often JWT)

  • The token is signed and optionally encrypted

  • The token is sent back to the client

Example response:

{ "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." }


Step 3: Client Uses Token

The client stores the token:

  • In memory

  • In localStorage

  • In sessionStorage

  • In cookies

For every subsequent request, the token is added to the header:

Authorization: Bearer <token>


Step 4: Server Validates Token

The server:

  • Verifies signature

  • Checks expiration

  • Validates claims

  • Grants or denies access


Step 5: Token Expiry & Refresh

Tokens usually expire after a defined time.

To avoid re-login:

  • A refresh token may be used

  • A new access token is generated


What Is JWT (JSON Web Token)?

JSON Web Token (JWT) is the most commonly used token format.

A JWT contains three parts:

  1. Header

  2. Payload

  3. Signature

Structure:

header.payload.signature

JWT is:

  • Compact

  • Secure

  • Digitally signed

  • Stateless

Because it is stateless, the server does not need to store session data.


Why Token-Based Authentication Is Important in Automation Testing

In real-world automation scenarios:

  • Login pages slow down test execution

  • UI-based login adds instability

  • API tests require authentication

  • Microservices require secure access

By handling token authentication programmatically:

  • You can skip UI login

  • You can test secured APIs directly

  • You can speed up test execution

  • You can build reusable test frameworks

This is where Playwright Java becomes powerful.


Handling Token-Based Authentication in Playwright Java

Playwright provides strong API testing support using APIRequestContext.

To handle token authentication in Playwright Java:

  1. Obtain token

  2. Store token

  3. Attach token to headers

  4. Call protected APIs

  5. Validate response

Let’s go step-by-step.


Example Scenario Using ReqRes API

We will use:

  • Login endpoint

  • Users endpoint

Provided by:

ReqRes

Login Endpoint:

https://reqres.in/api/login

Users Endpoint:

https://reqres.in/api/users/2


Maven Dependency

Add this dependency to your pom.xml:

<dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.44.0</version> </dependency>


Complete Java Code: Token-Based Authentication in 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()) { APIRequestContext 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; } // Step 2: Extract token String token = loginResponse.json().get("token").toString(); System.out.println("Token received: " + token); // Step 3: Use token in Authorization header 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 Explanation (Detailed)


Step 1: Create APIRequestContext

playwright.request().newContext();

This acts like an HTTP client.


Step 2: Send Login Request

request.post("https://reqres.in/api/login", ...)

We send credentials in JSON format.


Step 3: Extract Token

loginResponse.json().get("token").toString();

This retrieves the token from response JSON.


Step 4: Attach Token to Header

.setHeader("Authorization", "Bearer " + token)

This is the most important step.

Without this header, the server will deny access.


Step 5: Validate Protected Endpoint

We check:

  • Status code

  • Response body

If 200 → Success
If 401 → Unauthorized


Expected Output

Token received: QpwL5tke4Pnpja7X4 User API Status Code: 200 Token-based API access successful.


Using Token in Browser-Based Testing

For UI automation:

You may need to inject token into:

LocalStorage

page.evaluate("localStorage.setItem('token', '" + token + "')");


SessionStorage

page.evaluate("sessionStorage.setItem('token', '" + token + "')");


Cookies

context.addCookies(...)

After injecting the token, navigate to the application.

This bypasses login screen completely.


Reusing Authenticated State in Playwright

Playwright allows saving authentication state:

context.storageState(new BrowserContext.StorageStateOptions().setPath("auth.json"));

Later reuse:

browser.newContext(new Browser.NewContextOptions().setStorageStatePath(Paths.get("auth.json")));

This improves performance in large test suites.


Handling Token Expiry

Tokens expire for security reasons.

Best practices:

  1. Always generate token before test execution

  2. Store token temporarily

  3. Use refresh token flow if supported

  4. Avoid hardcoding tokens


Security Best Practices

Do Not Hardcode Credentials

Use:

  • Environment variables

  • Config files

  • CI/CD secrets


Use HTTPS Only

Tokens should never travel over HTTP.


Avoid Logging Sensitive Tokens

Do not print tokens in production logs.


Common Mistakes in Token-Based Testing

  • Forgetting "Bearer " prefix

  • Using expired tokens

  • Hardcoding token strings

  • Not validating login response

  • Mixing API and UI tokens incorrectly


When Should You Use Token-Based Authentication in Automation?

You should use token-based authentication when:

  • Testing REST APIs

  • Testing microservices

  • Bypassing UI login

  • Working with modern web applications

  • Testing secured endpoints


Advantages of Token-Based Authentication in Playwright

  • Faster test execution

  • More stable automation

  • Reduced UI dependency

  • Better scalability

  • Cleaner framework design


Final Thoughts

Token-based authentication is the backbone of modern API security. It provides a scalable, secure, and efficient way to manage user access without exposing credentials repeatedly.

By combining:

  • Token authentication

  • Playwright Java

  • APIRequestContext

  • State reuse

You can build a powerful and scalable automation framework capable of testing enterprise-level secure applications.

If you are serious about mastering API automation, understanding token-based authentication in Playwright Java is not optional—it is essential.


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

Test Basic Authentication in API by Playwright























What Is Basic Authentication? Complete Guide to Handling Basic Authentication in Playwright Java

In modern web applications and APIs, authentication plays a critical role in protecting sensitive data and restricting unauthorized access. One of the simplest and oldest authentication mechanisms used in web applications is Basic Authentication.

If you are working with automation testing using Playwright Java, understanding how to handle Basic Authentication efficiently is essential. In this detailed, SEO-optimized, and beginner-friendly guide, you will learn:

  • What Basic Authentication is

  • How it works behind the scenes

  • Where it is commonly used

  • How Playwright Java handles Basic Authentication

  • Step-by-step implementation with real example

  • Best practices and security considerations

This article is written in a clear, human tone and structured for easy understanding.


What Is Basic Authentication?

Basic Authentication is a simple authentication method used to verify a user’s identity using a username and password.

When a user tries to access a protected resource:

  1. The server asks for credentials.

  2. The client sends the username and password.

  3. The server validates the credentials.

  4. If valid, access is granted.

In technical terms, Basic Authentication works using the HTTP Authorization header.

How It Works Internally

When a user provides:

  • Username: user

  • Password: passwd

The browser combines them like this:

user:passwd

This string is encoded using Base64 and sent to the server in the HTTP header:

Authorization: Basic dXNlcjpwYXNzd2Q=

If the credentials are correct, the server responds with:

200 OK

If incorrect, the server responds with:

401 Unauthorized


Where Is Basic Authentication Used?

Basic Authentication is commonly used in:

  • Internal applications

  • Testing environments

  • Staging servers

  • Lightweight APIs

  • Admin panels

It is simple to implement and works well over HTTPS.

However, it is not recommended for highly sensitive production systems without additional security layers.


Why Is Basic Authentication Important in Automation Testing?

When performing automation testing:

  • Some web pages require login before access.

  • Some APIs require authentication headers.

  • Some staging servers use basic authentication as a protection layer.

If your automation framework cannot handle authentication properly, your tests will fail before even interacting with the application.

That’s where Playwright Java makes things easy.


How Playwright Java Handles Basic Authentication

Playwright provides a clean and centralized way to manage Basic Authentication.

Instead of manually adding the Authorization header in every request, Playwright allows you to configure credentials at the BrowserContext level.


What Is a BrowserContext in Playwright?

A BrowserContext in Playwright is like an isolated browser profile.

Each context:

  • Has its own cookies

  • Has its own session storage

  • Has its own authentication configuration

When you configure HTTP credentials inside a BrowserContext:

  • Every request automatically includes the authentication header.

  • You do not need to handle credentials repeatedly.

  • All pages, frames, and API calls inside that context inherit authentication.


Advantages of Using BrowserContext for Basic Authentication

1. Centralized Credential Handling

You define credentials once and reuse them across the entire test session.


2. No Manual Header Management

You don’t need to manually write:

Authorization: Basic <encoded-value>

Playwright handles it internally.


3. Works Across Pages and API Calls

Authentication automatically applies to:

  • Page navigation

  • Frame loading

  • API calls

  • AJAX requests


4. Cleaner and Maintainable Code

Credentials are not scattered across multiple test methods.


Step-by-Step: Testing Basic Authentication in Playwright Java

We will use the test website:

httpbin

Specifically, the URL:

https://httpbin.org/basic-auth/user/passwd

This endpoint requires:

  • Username: user

  • Password: passwd

If authentication is successful, it returns:

{ "authenticated": true, "user": "user" }


Complete Playwright Java Code Example

Below is the working Java example to test Basic Authentication.

import com.microsoft.playwright.*; public class BasicAuthTest { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { // Launch browser Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); // Configure HTTP Basic Authentication credentials Browser.NewContextOptions contextOptions = new Browser.NewContextOptions() .setHttpCredentials("user", "passwd"); // Create a new browser context with credentials BrowserContext context = browser.newContext(contextOptions); // Open a new page Page page = context.newPage(); // Navigate to protected URL page.navigate("https://httpbin.org/basic-auth/user/passwd"); // Verify authentication String bodyText = page.textContent("body"); if (bodyText.contains("\"authenticated\": true")) { System.out.println("Basic authentication successful!"); } else { System.out.println("Basic authentication failed."); } browser.close(); } } }


Code Explanation (Step-by-Step)

Let’s break it down clearly.


Step 1: Create Playwright Instance

Playwright playwright = Playwright.create();

This initializes the Playwright engine.


Step 2: Launch Browser

Browser browser = playwright.chromium().launch(...);

We launch the Chromium browser.

setHeadless(false) allows us to visually see the browser.
In CI environments, you can set it to true.


Step 3: Set HTTP Credentials

.setHttpCredentials("user", "passwd");

This is the most important step.

Instead of manually encoding credentials, Playwright does it internally.


Step 4: Create BrowserContext with Credentials

BrowserContext context = browser.newContext(contextOptions);

All pages created inside this context will automatically use authentication.


Step 5: Create Page Object

Page page = context.newPage();

Represents a browser tab.


Step 6: Navigate to Protected URL

page.navigate("https://httpbin.org/basic-auth/user/passwd");

Because credentials are already configured, Playwright automatically sends the Authorization header.


Step 7: Validate Authentication

bodyText.contains("\"authenticated\": true")

If authentication succeeds, the page contains:

"authenticated": true


Expected Output

Basic authentication successful!

This confirms that:

  • Credentials were sent correctly

  • Server validated them

  • Access was granted


Maven Dependency

Add this dependency in your pom.xml:

<dependency> <groupId>com.microsoft.playwright</groupId> <artifactId>playwright</artifactId> <version>1.44.0</version> </dependency>

Make sure Playwright browsers are installed using:

mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="install"


Handling Basic Authentication in API Testing

Playwright also supports API testing via APIRequestContext.

Example:

APIRequestContext request = playwright.request().newContext( new APIRequest.NewContextOptions() .setHttpCredentials("user", "passwd") );

Now all API requests from this context will include Basic Authentication.

This is extremely useful for:

  • REST API automation

  • Backend validation

  • Microservices testing


Security Considerations for Basic Authentication

While Basic Authentication is simple, it has limitations.

1. Always Use HTTPS

Basic Authentication sends credentials encoded in Base64.

Base64 is not encryption.

If sent over HTTP, credentials can be intercepted.

Always use HTTPS.


2. Avoid Hardcoding Credentials

Instead of:

.setHttpCredentials("user", "passwd")

Use environment variables:

System.getenv("USERNAME")

This improves security in CI/CD pipelines.


3. Rotate Credentials Regularly

Especially in shared test environments.


Common Mistakes in Basic Authentication Testing

  1. Forgetting HTTPS

  2. Adding manual Authorization headers unnecessarily

  3. Hardcoding credentials in test files

  4. Using wrong context for multiple tests

  5. Not isolating sessions properly


When Should You Use Basic Authentication in Automation?

Basic Authentication is ideal for:

  • Protecting staging environments

  • Securing test APIs

  • Internal dashboards

  • Quick login-based testing

However, modern applications often use:

  • Token-based authentication (JWT)

  • OAuth 2.0

  • Cookie-based sessions

But for simple authentication scenarios, Basic Authentication remains very effective.


Best Practices for Playwright Java Authentication

Use Dedicated Authentication Context

Create a reusable method:

public static BrowserContext createAuthenticatedContext(...) { }


Separate Credentials from Test Logic

Store in:

  • .env files

  • CI secrets

  • Configuration files


Use Headless Mode in CI

For performance and faster test execution.


Final Thoughts

Basic Authentication is one of the simplest and most widely used authentication mechanisms in web applications and APIs. While it may not be suitable for complex production environments, it remains highly useful in test environments and internal applications.

With Playwright Java, handling Basic Authentication is extremely simple and elegant. By configuring credentials at the BrowserContext level, you ensure:

  • Clean test architecture

  • Centralized credential management

  • Automatic header handling

  • Secure implementation

If you are building a scalable automation framework, mastering authentication handling in Playwright Java is essential.



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. Token Bsed Authentication in Playwright