Showing posts with label End-to-End Testing. Show all posts
Showing posts with label End-to-End Testing. Show all posts

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

How to Test Lombok API by Playwright


















What Is Lombok API? Complete Guide to Testing Lombok-Based APIs Using Playwright Java

Modern Java development often involves writing large amounts of repetitive code such as getters, setters, constructors, toString(), equals(), and hashCode() methods. This repetitive code, also known as boilerplate code, makes classes lengthy and harder to maintain. That is where Project Lombok becomes extremely useful.

In this detailed guide, you will learn:

  • What a Lombok API is

  • How Project Lombok works in Java

  • Why testing Lombok-based APIs is important

  • How to test Lombok-backed REST APIs using Playwright Java

  • A complete working example with code explanation

  • Best practices for API testing

This article is fully SEO-optimized, beginner-friendly, and written in a natural human tone to help developers understand Lombok API testing in depth.


1. What Is a Lombok API?

Before understanding a Lombok API, let’s first understand what Project Lombok is.

What Is Project Lombok?

Project Lombok is a popular Java library that reduces boilerplate code using annotations. Instead of manually writing repetitive methods, Lombok automatically generates them at compile time.

Common Lombok Annotations

Some of the most commonly used Lombok annotations include:

  • @Getter

  • @Setter

  • @Data

  • @Builder

  • @NoArgsConstructor

  • @AllArgsConstructor

  • @ToString

  • @EqualsAndHashCode

For example:

import lombok.Data; @Data public class User { private int id; private String name; private String email; }

With just @Data, Lombok automatically generates:

  • Getters and setters

  • toString()

  • equals()

  • hashCode()

  • Required constructors

This significantly improves code readability and maintainability.


2. What Do We Mean by “Lombok API”?

When developers refer to a Lombok API, they usually mean:

A REST API whose backend models (DTOs or entities) use Lombok annotations.

For example, consider a Spring Boot backend:

@Data @Builder public class UserDTO { private Long id; private String name; private String email; }

If this DTO is used in a REST controller, then the API is indirectly powered by Lombok.

Important point:

👉 Lombok runs at compile time and generates bytecode.
👉 From a testing perspective, the API behaves like any normal REST API.
👉 The test automation tool does not “see” Lombok directly.

However, we must still test the behavior that depends on Lombok-generated methods.


3. Why Testing Lombok-Based APIs Is Important

Although Lombok reduces boilerplate, improper usage can cause unexpected issues.

Key Reasons to Test Lombok APIs

1. Validate Getter and Setter Methods

Lombok generates these methods automatically. But if annotations are misconfigured, fields may not behave correctly.

2. Validate equals() and hashCode()

If @EqualsAndHashCode or @Data is used incorrectly:

  • Objects may behave incorrectly in collections like HashSet

  • Duplicate detection may fail

  • Map keys may not work properly

3. Validate toString() Output

For logging and debugging, a meaningful toString() is critical.

4. Validate @Builder Pattern

If @Builder is used:

  • Ensure all required fields are set

  • Ensure object construction works as expected

  • Validate JSON serialization matches API contract

5. Validate Serialization & Deserialization

Lombok-generated models are often serialized into JSON. If misconfigured:

  • JSON fields may be missing

  • Naming conventions may mismatch

  • API contract may break


4. How to Test Lombok APIs Using Playwright Java

Now let’s discuss how to test a Lombok-powered REST API using Playwright Java.

Although Playwright is primarily known for UI automation, it also provides strong API testing capabilities using APIRequestContext.

However, in many enterprise projects, developers also use:

  • Java HttpClient

  • RestAssured

  • OkHttp

In this guide, we will use:

  • Playwright Java

  • Java HttpClient


5. Steps to Test a Lombok-Based API

Here’s the structured approach:

Step 1: Set Up Playwright Java Project

Add Maven dependency:

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

Make sure Java 11+ is installed.


Step 2: Understand the Example API

Assume we have a backend API built using Lombok models.

API Endpoint

POST http://localhost:8080/api/users

Request Body

{ "name": "John Doe", "email": "john@example.com" }

Response

{ "id": 1, "name": "John Doe", "email": "john@example.com" }

The backend uses Lombok annotations like @Data and @Builder.


6. Complete Java Code to Test Lombok API

Here is a working example using Playwright Java + HttpClient:

import com.microsoft.playwright.*; import java.net.URI; import java.net.http.*; import java.net.http.HttpResponse.BodyHandlers; import java.net.http.HttpRequest.BodyPublishers; public class LombokApiTest { public static void main(String[] args) throws Exception { // Start Playwright try (Playwright playwright = Playwright.create()) { Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(true)); BrowserContext context = browser.newContext(); Page page = context.newPage(); // Create HttpClient HttpClient client = HttpClient.newHttpClient(); // JSON Request Body String jsonBody = """ { "name": "John Doe", "email": "john@example.com" } """; // Create HTTP Request HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8080/api/users")) .header("Content-Type", "application/json") .POST(BodyPublishers.ofString(jsonBody)) .build(); // Send Request HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); // Print Response System.out.println("Status Code: " + response.statusCode()); System.out.println("Response Body: " + response.body()); // Validate Status if (response.statusCode() == 200 || response.statusCode() == 201) { System.out.println("API Test Passed"); } else { System.out.println("API Test Failed"); } browser.close(); } } }


7. Code Explanation (Step-by-Step)

(a) Create Playwright Instance

Playwright playwright = Playwright.create();

This initializes Playwright.


(b) Launch Browser (Optional)

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

We use this if we want to verify the UI after API execution.


(c) Create Java HttpClient

HttpClient client = HttpClient.newHttpClient();

This is used to send HTTP requests.


(d) Define JSON Request Body

We prepare the payload that will be sent to the Lombok-backed API.


(e) Build and Send HTTP Request

HttpRequest request = HttpRequest.newBuilder()...

Then:

client.send(request, BodyHandlers.ofString());


(f) Validate Response

We check:

  • Status Code (200 or 201)

  • Response Body content


8. How Lombok Affects API Testing

Even though Lombok is not directly visible in API testing, its generated methods impact:

1. Object Creation

If backend uses:

@Builder public class UserDTO { ... }

We must validate that:

  • Required fields are not null

  • Builder sets values correctly

  • API returns correct JSON


2. Equality Checks

If @EqualsAndHashCode is used:

  • Duplicate users should not exist

  • API must behave correctly in list operations


3. JSON Serialization

If Lombok fields are private and getters are generated:

  • JSON must include expected keys

  • Field names must match API contract


9. Advanced Validation in API Testing

Instead of just checking status codes, you should validate:

Validate JSON Fields

Example (pseudo validation):

  • Ensure response contains "name": "John Doe"

  • Ensure "id" is not null

  • Ensure email format is correct


Validate Data Consistency

After POST:

  1. Call GET /api/users/{id}

  2. Ensure returned data matches inserted data


Negative Testing

Test error scenarios:

  • Missing email

  • Invalid format

  • Duplicate entries

Expected responses:

  • 400 Bad Request

  • 409 Conflict

  • 422 Unprocessable Entity


10. Best Practices for Testing Lombok APIs

1. Don’t Assume Lombok Always Works

Even though Lombok generates code, test behavior thoroughly.


2. Always Validate API Contract

Use schema validation if possible.


3. Test Builder Patterns Carefully

Ensure:

  • Required fields are enforced

  • Optional fields behave correctly


4. Combine API and UI Testing

With Playwright, you can:

  • Create user via API

  • Validate user appears in UI

This ensures end-to-end validation.


5. Use Assertions Framework

For production projects, use:

  • JUnit

  • TestNG

  • AssertJ

Instead of simple if statements.


11. Tools Used in This Setup

Java HttpClient

Used for sending REST requests.

Playwright Java

Used for:

  • UI automation

  • API testing

  • End-to-end testing

Lombok (Backend Only)

Used to:

  • Reduce boilerplate

  • Generate model methods

  • Improve maintainability


12. Common Mistakes When Testing Lombok APIs

  1. Ignoring equals/hashCode behavior

  2. Not validating builder-generated objects

  3. Skipping negative testing

  4. Only checking status code

  5. Not verifying serialization output


13. Final Thoughts

Testing a Lombok-based API is fundamentally the same as testing any REST API. However, because Lombok generates methods at compile time, it is essential to validate that:

  • Generated getters/setters work correctly

  • Builder pattern constructs valid objects

  • JSON serialization matches expected API contract

  • equals() and hashCode() behave properly

Using Playwright Java along with Java HttpClient provides a powerful and flexible solution for testing REST APIs.

By following structured API testing practices, validating both positive and negative scenarios, and combining backend and frontend validation, you can build reliable, maintainable, and production-ready automation frameworks.


Suggested Posts:

1. Automate GET API in Playwright
2. Automate POST API in Playwright
3. Automate PUT API in Playwright
4. Test Basic Authentication in Playwright
5. Test API by POJO Class in Playwright