Showing posts with label API Testing in Playwright. Show all posts
Showing posts with label API Testing in Playwright. Show all posts

How to Test Cookie based Authentication in API by Playwright















Cookie-Based Authentication in Playwright Java – Complete Guide with Example

Authentication is one of the most important aspects of web application testing. Almost every modern web application requires users to log in before accessing protected features. In real-world automation projects, handling authentication properly is critical for building stable, scalable, and efficient test suites.

In this comprehensive guide, you will learn:

  • What cookies are

  • What cookie-based authentication is

  • How cookie authentication works internally

  • Why it is important in automation

  • How to handle cookie-based authentication in Playwright Java

  • A complete working Java example using Playwright

  • Best practices for managing cookies in automation

This guide is fully beginner-friendly, SEO optimized, and written in a human-like, easy-to-understand format.


What Are Cookies?

Cookies are small pieces of data stored by a web browser on the client side. They are typically sent by the server through HTTP response headers and then stored by the browser. On subsequent requests to the same domain, the browser automatically attaches these cookies back to the server.

In simple words, cookies help websites “remember” users.

Why Are Cookies Used?

Cookies serve multiple purposes in modern web applications:

  • Session Management

    • Login sessions

    • User preferences

    • Shopping carts

  • Personalization

    • Themes

    • Language settings

    • Recommendations

  • Tracking and Analytics

    • User behavior tracking

    • Advertising

    • Performance monitoring

Without cookies, users would have to log in again every time they navigate to a new page.


What Is Cookie-Based Authentication?

Cookie-based authentication is a mechanism where the server authenticates a user and creates a session. Instead of sending credentials repeatedly, the server generates a unique session ID and stores it on the server side. This session ID is then sent to the client as a cookie.

The browser automatically sends this cookie with every subsequent request, allowing the server to recognize the authenticated user.

How Cookie-Based Authentication Works

Let’s break it down step by step:

  1. User provides login credentials
    The user enters username and password.

  2. Server verifies credentials
    If credentials are correct, the server creates a session.

  3. Server generates a session ID
    This session ID is stored in server memory or database.

  4. Server sends Set-Cookie header
    The session ID is sent back to the browser.

  5. Browser stores the cookie
    The browser saves it automatically.

  6. Browser sends cookie in future requests
    The server checks the session ID and allows access.

This method is widely used in traditional web applications.


Why Cookie-Based Authentication Is Important in Automation

In automation testing, logging in repeatedly for every test case is inefficient and unstable. UI login flows can slow down your test suite and introduce unnecessary failures.

Handling cookies correctly provides:

1. Efficiency

You can log in once and reuse the authenticated session.

2. Stability

Avoid flaky login UI interactions.

3. Scalability

Multiple tests can reuse the same authenticated state.

4. Faster Execution

Skipping login reduces overall test runtime significantly.

This is especially useful in enterprise applications where login includes CAPTCHA, MFA, or complex flows.


Handling Cookie-Based Authentication in Playwright (Java)

Playwright provides powerful capabilities to handle authentication. In Java, cookie-based authentication can be handled in two primary ways.


Method 1: Manual Login Once and Reuse Cookies

This is the most commonly used approach in automation frameworks.

Steps:

  1. Automate login using UI.

  2. Extract cookies from the browser context.

  3. Save cookies into a JSON file.

  4. Reuse cookies in future test sessions.

This approach is ideal for regression test suites.


Method 2: Programmatic Cookie Injection

If you already have valid cookies, you can:

  • Directly inject cookies into the browser context.

  • Skip the login page entirely.

  • Navigate directly to protected resources.

This method is faster and preferred in CI/CD environments.


Practical Example: Cookie-Based Authentication Using Playwright Java

For demonstration, we will use:

SauceDemo

Website URL:
https://www.saucedemo.com/

It is a simple demo e-commerce site that sets authentication cookies after login.

Test Credentials:

  • Username: standard_user

  • Password: secret_sauce


Maven Dependency for Playwright

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: Cookie-Based Authentication in Playwright

import com.microsoft.playwright.*; import java.nio.file.Paths; import java.util.List; public class CookieAuthTest { public static void main(String[] args) { String storageStatePath = "auth.json"; try (Playwright playwright = Playwright.create()) { Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); BrowserContext context = browser.newContext(); Page page = context.newPage(); // Step 1: Navigate to login page page.navigate("https://www.saucedemo.com/"); // Step 2: Perform login page.locator("[name='user-name']").fill("standard_user"); page.locator("[name='password']").fill("secret_sauce"); page.locator("[name='login-button']").click(); // Step 3: Wait for successful login page.waitForURL("**/inventory.html"); // Step 4: Save storage state (cookies + localStorage) context.storageState( new BrowserContext.StorageStateOptions() .setPath(Paths.get(storageStatePath)) ); // Step 5: Extract cookies List<BrowserContext.Cookie> cookies = context.cookies(); System.out.println("Extracted Cookies:"); for (BrowserContext.Cookie cookie : cookies) { System.out.println(cookie.name + " = " + cookie.value); } // Step 6: Create new context with saved cookies BrowserContext authContext = browser.newContext( new Browser.NewContextOptions() .setStorageStatePath(Paths.get(storageStatePath)) ); Page authPage = authContext.newPage(); authPage.navigate("https://www.saucedemo.com/inventory.html"); // Step 7: Validate access to protected page if (authPage.locator(".header_label").isVisible()) { System.out.println("Authentication successful using cookie!"); } else { System.out.println("Authentication failed."); } browser.close(); } } }


Step-by-Step Code Explanation

(a) Create Playwright Instance

Playwright playwright = Playwright.create();

Initializes Playwright engine.

(b) Launch Browser

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

Launches Chromium browser.

(c) Create Browser Context

A BrowserContext acts as an isolated browser session.

(d) Perform Login

Using:

page.locator().fill()

Simulates real user interaction.

(e) Wait for Navigation

page.waitForURL("**/inventory.html");

Confirms successful login.

(f) Save Storage State

context.storageState()

Stores:

  • Cookies

  • LocalStorage

  • SessionStorage

(g) Create New Authenticated Context

setStorageStatePath(Paths.get(storageStatePath))

Reuses saved session.

(h) Validate Authentication

Checks if protected element is visible.


Why Use storageState Instead of Only Cookies?

Playwright allows saving:

  • Cookies

  • LocalStorage

  • SessionStorage

Modern applications often store tokens in localStorage instead of cookies. Saving the entire storage state ensures complete authentication.


Best Practices for Cookie-Based Authentication in Playwright

1. Save Authentication State Once

Generate auth file in a setup test.

2. Reuse Auth State in All Tests

Load storage state for test execution.

3. Avoid Hardcoding Credentials

Use environment variables.

4. Handle Expired Sessions

Regenerate auth file if session expires.

5. Use Headless Mode in CI/CD

Set:

.setHeadless(true)


Common Issues and Solutions

Issue: Session Expires Frequently

Solution:

  • Regenerate authentication before suite execution.

Issue: Cookies Not Working in New Context

Solution:

  • Ensure correct domain.

  • Confirm secure/HTTP-only flags.

Issue: Login Redirect Loop

Solution:

  • Verify storage state is correctly loaded.


Cookie-Based Authentication vs Token-Based Authentication

FeatureCookie-BasedToken-Based
StorageBrowser cookieLocalStorage/Header
Server StorageSession stored server-sideUsually stateless
SecurityCSRF protection neededRequires token security
AutomationEasy with storageStateRequires header injection

Both methods are widely used in web applications.


Advantages of Using Cookie Authentication in Playwright

  • Simple implementation

  • Realistic browser simulation

  • Reduced login flakiness

  • Faster test execution

  • Easy session reuse

For enterprise automation frameworks, cookie reuse is a must-have optimization strategy.


When Should You Use Cookie-Based Authentication?

Use it when:

  • Testing web UI applications

  • Running regression suites

  • Working with session-based apps

  • You want faster automation runs

  • Login flow is complex or unstable


Conclusion

Cookie-based authentication is one of the most common and reliable authentication mechanisms used in web applications. Understanding how cookies work and how to handle them in automation is essential for building robust Playwright Java test frameworks.

With Playwright, managing authentication becomes straightforward using:

  • BrowserContext

  • Cookies extraction

  • storageState reuse

  • Programmatic injection

By implementing cookie-based authentication properly, you can:

  • Improve test stability

  • Speed up execution

  • Reduce flaky login failures

  • Scale automation efficiently

If you are building a professional test automation framework in Java, mastering cookie handling in Playwright is a critical skill.



Suggested Posts:

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

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