Showing posts with label Playwright Tips & Tricks. Show all posts
Showing posts with label Playwright Tips & Tricks. 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

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