PRACTICAL GUIDE / Selenium BiDi network interception

Intercept Requests and Supply Authentication with Selenium BiDi Network

Use Selenium BiDi network intercepts for scoped Basic or Digest authentication, request control, response evidence, cleanup, and safe diagnostics.

By The Testing AcademyUpdated July 11, 20269 min read
All field guides
In this guide12 sections
  1. Choose the Correct Network Phase
  2. Enable BiDi and Scope the Module
  3. Supply HTTP Authentication Credentials
  4. Defend Every Handler Branch
  5. Modify Requests Only When the Test Requires It
  6. Observe Responses Without Confusing Them with Success
  7. Test Negative Authentication Paths
  8. Keep Secrets Out of Evidence
  9. Clean Up Intercepts and Listeners
  10. Diagnose Network Interception Failures
  11. Network Intercept Checklist
  12. Control the Request, Then Prove the Authorization

What you will learn

  • Choose the Correct Network Phase
  • Enable BiDi and Scope the Module
  • Supply HTTP Authentication Credentials
  • Defend Every Handler Branch

Network interception is a control point, not a shortcut for every login. Selenium BiDi can pause a browser request at a defined phase, inspect the event, and tell the browser how to proceed. For HTTP authentication challenges, that means credentials can be supplied without putting user:password in a URL or automating a native prompt.

The safety rule is uncompromising: every blocked request must receive exactly one terminal decision. A handler that returns without continuing, authenticating, canceling, failing, or providing a response leaves the browser waiting. Scope intercepts narrowly, keep credentials outside source, and remove each intercept as soon as its workflow ends.

Choose the Correct Network Phase

BiDi network interception has phases such as before a request is sent, response started, and authentication required. Use AUTH_REQUIRED when the browser has received an HTTP authentication challenge and needs credentials. Use BEFORE_REQUEST_SENT when the scenario truly needs to block or modify an outgoing request. Observing an event without blocking can use the corresponding event listener instead of an intercept.

The Selenium BiDi network documentation distinguishes authentication, request, and response handlers. The W3C BiDi contract makes blocked state explicit, so handler code must be total: every event that reaches it needs a deliberate outcome.

Animated field map

BiDi Network Intercept Decision

A browser request reaches a scoped BiDi event, the handler makes one terminal decision, and the test verifies both response and authorized product state.

  1. 01 / browser request

    Browser Request

    Navigation or page code issues a request in the selected browsing context.

  2. 02 / network event

    BiDi Network Event

    The browser emits a request or authentication-required event with request identity.

  3. 03 / intercept decision

    Intercept Decision

    Validate URL, phase, context, and the single allowed handling path.

  4. 04 / request resolution

    Credentials or Request

    Continue with credentials, continue or modify the request, cancel, or fail.

  5. 05 / response assertion

    Response Assertion

    Prove the expected principal and protected product state, then remove the intercept.

Enable BiDi and Scope the Module

Request webSocketUrl before creating the session. Build the Java Network module with the current window handle when only one top-level context should be affected. A module created with the driver alone can observe more broadly, which may authenticate a background tab or popup that the test did not intend to trust.

Do not register an intercept until the test-only credential and target host have been validated. If setup fails after registration, cleanup still needs the intercept ID. Keep registration and removal in one lexical scope.

Supply HTTP Authentication Credentials

The Java example uses an AUTH_REQUIRED intercept restricted to one HTTPS host. It validates the actual event URL again before providing credentials, counts challenges without logging their payload, and removes the intercept in finally.

Java
import static java.util.Objects.requireNonNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.net.URI;
import java.util.concurrent.atomic.AtomicInteger;
import org.openqa.selenium.By;
import org.openqa.selenium.UsernameAndPassword;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.bidi.module.Network;
import org.openqa.selenium.bidi.network.AddInterceptParameters;
import org.openqa.selenium.bidi.network.InterceptPhase;
import org.openqa.selenium.bidi.network.UrlPattern;

String username = requireNonNull(System.getenv("BASIC_AUTH_USER"));
String password = requireNonNull(System.getenv("BASIC_AUTH_PASSWORD"));
String allowedHost = "secure.example.test";
AtomicInteger challenges = new AtomicInteger();

try (Network network = new Network(driver.getWindowHandle(), driver)) {
  AddInterceptParameters parameters =
      new AddInterceptParameters(InterceptPhase.AUTH_REQUIRED)
          .urlPattern(new UrlPattern().protocol("https").hostname(allowedHost));

  String interceptId = network.addIntercept(parameters);
  network.onAuthRequired(details -> {
    String requestId = details.getRequest().getRequestId();
    URI requestUrl = URI.create(details.getRequest().getUrl());

    if (allowedHost.equalsIgnoreCase(requestUrl.getHost())) {
      challenges.incrementAndGet();
      network.continueWithAuth(
          requestId, new UsernameAndPassword(username, password));
    } else {
      network.continueWithAuthNoCredentials(requestId);
    }
  });

  try {
    driver.get("https://secure.example.test/reports");
    assertTrue(challenges.get() > 0, "Expected an HTTP auth challenge");
    assertTrue(driver.findElement(By.cssSelector("[data-testid='reports']")).isDisplayed());
  } finally {
    network.removeIntercept(interceptId);
  }
}

This flow is for browser-managed HTTP authentication. An HTML form should be tested through its form or an approved application login fixture. OAuth and SAML require their redirect, state, nonce, and session contracts. Client certificates require a different browser and environment setup. Using the wrong mechanism can produce a green test that bypasses the security behavior under review.

Defend Every Handler Branch

URL patterns reduce event volume but are not authorization. Check scheme, normalized host, expected port, and path when deciding whether a secret may be used. Avoid suffix checks such as endsWith("example.test") without a hostname boundary; a hostile hostname can be crafted to satisfy loose text comparisons.

If the event is not eligible, continue without credentials or cancel according to the scenario. Do not throw before resolving the blocked request and assume Selenium will recover. Capture the policy error, send the safe terminal decision, then make the test fail on the captured error after the callback returns.

Callbacks run on the BiDi event path. They must not wait for WebDriver commands, fetch secrets over a slow network, or perform a UI assertion. Resolve secrets before navigation and put only immutable policy data in the handler.

Modify Requests Only When the Test Requires It

A BEFORE_REQUEST_SENT intercept can continue a request unchanged or provide modified URL, method, headers, cookies, or body through ContinueRequestParameters. Modification is useful for testing feature headers, controlled fault routing, or a product-owned proxy contract. It is not a general substitute for configuring the application normally.

When supplying a headers list, treat it as a replacement contract and preserve every original header the request still needs. Do not casually add Authorization to all matching requests; redirects can change hosts, and secrets can leak. Prefer the authentication-required flow for HTTP auth because the browser applies the challenge semantics.

Every BEFORE_REQUEST_SENT callback must call continueRequest, failRequest, or another valid terminal command exactly once. Put decision construction in a pure function that can be unit tested with URLs and methods, leaving the callback responsible only for applying the decision.

Observe Responses Without Confusing Them with Success

onResponseStarted and onResponseCompleted can collect typed response evidence. Use a thread-safe queue and filter by request URL, browsing context, and request ID. Redirect chains produce multiple requests, so a URL match alone may not identify the final protected resource.

A successful response is transport evidence. The functional verdict still needs product state and identity: the protected page is rendered, the expected user or service account is active, forbidden actions remain forbidden, and a server-side test endpoint confirms the principal where available. Authentication without authorization is not a complete security assertion.

Test Negative Authentication Paths

Create separate cases for correct credentials, incorrect credentials, no credentials, and an unexpected host challenge. For incorrect credentials, assert that protected content is absent and that the application or browser reaches the expected unauthorized outcome. Do not assert browser prompt text across platforms unless that text is itself a supported product contract.

Also test redirect handling. A protected endpoint may redirect to another origin after authentication. The credential handler must not follow that redirect with secrets unless the second origin is independently allowlisted. Keep test credentials minimally privileged so a handler defect has limited impact.

Keep Secrets Out of Evidence

Never log UsernameAndPassword, authentication headers, full request headers, or URLs containing sensitive query data. A network timeline should include request ID, sanitized origin and path, phase, decision type, response status, and timing. Store raw captures only under an explicit security policy when they are genuinely needed.

Resolve credentials from a secret provider before adding the listener. Clear references when the test framework permits, and use accounts dedicated to the environment. Screenshots after failed HTTP auth may show browser-native prompts or usernames, so apply the same artifact access and retention controls used for other authentication tests.

Clean Up Intercepts and Listeners

Removing the intercept stops future requests from being blocked by that intercept. Closing the Network module clears its owned event listeners. Do both at the narrowest useful scope, then quit the driver. A shared browser fixture must finish cleanup before another test navigates, or the old handler can authenticate the new test accidentally.

If removal fails because the session died, report cleanup as incomplete but preserve the original test failure. The remote session ending will eventually remove protocol state, yet a failed cleanup still matters when session reuse or provider capacity is involved.

Diagnose Network Interception Failures

A page that hangs with isBlocked events points to a missing terminal decision. No authRequired event suggests that no challenge occurred, the intercept URL pattern missed, the wrong context was scoped, or the remote browser lacks the needed support. Repeated challenges after credentials were supplied indicate rejection, an unexpected credential realm, or another protected subresource.

An event arriving for the wrong host is a policy and scoping defect. A response completing while protected UI is absent is an application or authorization issue, not proof that BiDi failed. Preserve sanitized event phase, request ID, context, redirect count, host, decision, and response outcome to locate the boundary.

Network Intercept Checklist

  • Request and verify BiDi before constructing the network module.
  • Choose the interception phase that matches the behavior under test.
  • Scope by browsing context and a narrow URL pattern.
  • Validate the actual event URL before applying credentials or mutation.
  • Resolve secrets before the callback and never log them.
  • Give every blocked request exactly one terminal decision.
  • Keep callback work short and free of WebDriver calls.
  • Assert protected product state and the expected principal.
  • Cover wrong credentials, absent credentials, redirects, and unexpected hosts.
  • Remove the intercept and close listeners before fixture reuse.

Control the Request, Then Prove the Authorization

A sound BiDi network test makes interception temporary and reviewable. It pauses only the intended request, applies one safe decision, exposes no credentials, and proves the resulting user authorization rather than merely observing a response. Design that contract first; the Selenium API then becomes a precise transport for the security scenario instead of an invisible bypass.

// LIVE COURSE / THE TESTING ACADEMY

Playwright Automation Mastery

Go beyond Selenium. Master Playwright with JS/TS in 90 days.

From the instructor behind this guide.

Playwright jobs are growing 8x faster than Selenium. 90 days / 75+ live hrs / Tue-Thu-Sat 7 AM IST.

Code PROMODE / 10% offJoin the batch

The Testing Academy editorial desk

Practical QA guidance built around test evidence, production tradeoffs, and interview-ready explanations.

Published July 11, 2026 / Reviewed July 11, 2026

PRIMARY REFERENCES

Verify the details at the source

QABattle guides are practical explanations. Product behavior, standards, and APIs can change, so use these primary references for the canonical details.

  1. 01
    Selenium documentation

    Selenium Project

    Canonical WebDriver, Grid, waits, element, and browser automation guidance.

  2. 02
    WebDriver standard

    W3C

    The browser automation protocol specification behind WebDriver implementations.

  3. 03
    Web Security Testing Guide

    OWASP Foundation

    Primary testing scenarios for identity, authorization, input validation, and web security controls.

  4. 04
    OWASP Top 10

    OWASP Foundation

    Current high-level web application security risk taxonomy.

FAQ / QUICK ANSWERS

Questions testers ask

What authentication can a WebDriver BiDi auth handler supply?

The network authentication flow is intended for browser HTTP authentication challenges such as Basic or Digest. It is not a replacement for HTML login forms, OAuth redirects, client certificates, or application token exchange.

Why does a page hang after I add a network intercept?

An intercepted request is blocked until the handler continues it, continues with credentials, continues without credentials, fails it, cancels authentication, or provides a response where supported. Every matched path needs one terminal decision.

Should credentials be embedded in the Selenium test?

No. Resolve test-only credentials from the CI secret store, scope the intercept to the exact test host, never log the values, and rotate them under the same policy as other automation credentials.

Can one intercept modify only a single request?

Scope the intercept with a URL pattern and browsing context, then remove it immediately after the target workflow. The handler must still defend against unexpected matched URLs before changing or authenticating a request.

How should a test prove authentication succeeded?

Assert the protected product state and a server-observable identity or authorization result. A completed navigation or a network response alone does not prove that the correct principal received the correct access.