Implementation:SeleniumHQ Selenium HasAuthentication
| Knowledge Sources | |
|---|---|
| Domains | WebDriver, Capabilities |
| Last Updated | 2026-02-12 00:00 GMT |
Overview
Concrete tool for registering authentication credentials with a WebDriver session provided by the Selenium WebDriver library.
Description
HasAuthentication is an interface that indicates a driver supports authenticating to websites. It provides a register method that accepts a URI predicate and a credentials supplier, allowing conditional credential matching against request URIs. When multiple credentials are registered, they are checked in registration order and the first matching predicate is used. A convenience default method allows registering credentials that apply to all authentication requests unconditionally.
Usage
Import and use HasAuthentication when you need to handle HTTP Basic or similar authentication dialogs programmatically during browser automation. Cast a WebDriver instance to HasAuthentication and register the appropriate Credentials (typically UsernameAndPassword) with optional URI-based filtering.
Code Reference
Source Location
- Repository: SeleniumHQ_Selenium
- File: java/src/org/openqa/selenium/HasAuthentication.java
Signature
public interface HasAuthentication {
void register(Predicate<URI> whenThisMatches, Supplier<Credentials> useTheseCredentials);
default void register(Supplier<Credentials> alwaysUseTheseCredentials);
}
Import
import org.openqa.selenium.HasAuthentication;
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| whenThisMatches | Predicate<URI> |
Yes | A predicate that tests whether the given credentials should be used for a particular site URI |
| useTheseCredentials | Supplier<Credentials> |
Yes | A supplier that provides the credentials to use when the predicate matches |
| alwaysUseTheseCredentials | Supplier<Credentials> |
Yes | A supplier of credentials that will be applied to any authentication request (convenience overload) |
Outputs
| Name | Type | Description |
|---|---|---|
| (void) | void |
Both register methods return void; they register credentials as a side effect on the driver
|
Usage Examples
WebDriver driver = new ChromeDriver();
// Register credentials for a specific domain
if (driver instanceof HasAuthentication) {
((HasAuthentication) driver).register(
uri -> uri.getHost().contains("example.com"),
() -> new UsernameAndPassword("admin", "secretPassword")
);
}
// Register credentials for all authentication requests
if (driver instanceof HasAuthentication) {
((HasAuthentication) driver).register(
() -> new UsernameAndPassword("user", "pass")
);
}
// Navigate to a page that requires authentication
driver.get("https://example.com/protected");