Popular Searches
Popular Course Categories
Popular Courses

Authentication Handling

Authentication Handling

Advanced Selenium

Authentication Handling in Selenium

Authentication Handling in Selenium refers to the techniques used to automate web applications and protected resources that require user authentication before allowing access. Authentication may be implemented through normal HTML login forms, HTTP Basic Authentication, Digest Authentication, session cookies, tokens, OAuth-based flows, or other mechanisms.

In Selenium automation, authentication handling is important because many real-world applications require a user to authenticate before accessing dashboards, admin panels, customer portals, APIs, or protected pages. The automation framework must be able to provide valid authentication information and then verify that access was granted successfully.

For normal form-based authentication, Selenium can interact directly with username and password fields using locators. For browser-level HTTP authentication prompts, Selenium 4 provides authentication-related capabilities through modern network and WebDriver BiDi mechanisms.

Course Resource: Selenium Training | Register for Course Demo


1. What is Authentication?

Authentication is the process of verifying the identity of a user, system, or application before granting access to a protected resource.

A typical authentication process verifies information such as a username, password, authentication token, session identifier, or other credentials.

User

  |

  v

Enter Credentials

  |

  v

Authentication System

  |

  +---- Valid ----> Access Granted

  |

  +---- Invalid --> Access Denied


2. Authentication vs Authorization

Authentication determines who the user is, while authorization determines what that authenticated user is allowed to access.

AuthenticationAuthorization
Verifies identityVerifies permissions
Usually occurs during loginUsually occurs after authentication
Example: username and passwordExample: Admin can delete users
Answers "Who are you?"Answers "What can you access?"


3. Why Authentication Handling is Important in Selenium

  • Many applications require login before testing functionality.
  • Admin applications are usually protected.
  • Customer portals require authenticated sessions.
  • Authentication may be required before accessing specific pages.
  • Different user roles may require different credentials.
  • Regression tests frequently need authenticated access.
  • Authentication is commonly required in end-to-end automation.
  • Protected APIs and web resources may use HTTP authentication.


4. Common Types of Authentication

Authentication TypeDescriptionTypical Automation Approach
Form-Based AuthenticationHTML login formLocate fields and submit form
HTTP Basic AuthenticationBrowser/server authentication challengeSelenium authentication handling or network authentication
Digest AuthenticationChallenge-response HTTP authenticationNetwork/authentication mechanisms
Cookie-Based SessionAuthenticated state stored in cookiesCookie management
Token-Based AuthenticationAuthentication based on tokensToken/session setup
OAuthDelegated authorization/authentication flowControlled authentication flow or pre-authenticated state
Multi-Factor AuthenticationMultiple verification factorsTest-specific MFA strategy


5. Authentication Handling Flow

Start Test

   |

   v

Open Application

   |

   v

Authentication Required?

   |

   +---- No ----> Continue Test

   |

   +---- Yes

          |

          v

   Select Authentication Strategy

          |

          v

   Provide Credentials

          |

          v

   Authentication Completed

          |

          v

   Validate Authenticated State

          |

          v

   Continue Test Execution


6. Form-Based Authentication

Form-based authentication is one of the most common authentication mechanisms in web applications. The application displays an HTML form containing fields such as username, password, and a login button.

driver.findElement(By.id("username"))

        .sendKeys("testuser");

 

driver.findElement(By.id("password"))

        .sendKeys("password");

 

driver.findElement(By.id("loginButton"))

        .click();

Selenium can interact with these elements because they belong to the web page's DOM.


7. Complete Form-Based Login Example

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class LoginTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

        driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://example.com/login");

    }

 

    @Test

    public void loginTest() {

 

        driver.findElement(By.id("username"))

                .sendKeys("testuser");

 

        driver.findElement(By.id("password"))

                .sendKeys("testpassword");

 

        driver.findElement(By.id("loginButton"))

                .click();

 

        Assert.assertTrue(

                driver.getTitle().contains("Dashboard")

        );

    }

 

    @AfterMethod

    public void tearDown() {

        if (driver != null) {

            driver.quit();

        }

    }

}


8. Handling Authentication Using Page Object Model

In a maintainable Selenium framework, authentication logic should normally be placed inside a dedicated Page Object rather than duplicated in every test class.

public class LoginPage {

 

    private WebDriver driver;

 

    private By usernameField = By.id("username");

    private By passwordField = By.id("password");

    private By loginButton = By.id("loginButton");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void enterUsername(String username) {

        driver.findElement(usernameField).sendKeys(username);

    }

 

    public void enterPassword(String password) {

        driver.findElement(passwordField).sendKeys(password);

    }

 

    public void clickLogin() {

        driver.findElement(loginButton).click();

    }

 

    public void login(String username, String password) {

        enterUsername(username);

        enterPassword(password);

        clickLogin();

    }

}


9. Using Authentication in a Test Class

public class LoginTest {

 

    WebDriver driver;

 

    @Test

    public void validLoginTest() {

 

        driver = new ChromeDriver();

        driver.get("https://example.com/login");

 

        LoginPage loginPage = new LoginPage(driver);

 

        loginPage.login(

                "testuser",

                "testpassword"

        );

    }

}


10. What is HTTP Basic Authentication?

HTTP Basic Authentication is an HTTP authentication mechanism in which a protected resource challenges the client for credentials. Unlike a normal HTML login form, the authentication prompt can be generated by the browser/network layer rather than being an HTML element in the page DOM.

This distinction is important because normal Selenium commands such as findElement() are intended for elements in the web page DOM and cannot directly locate browser-level authentication dialogs.


11. Basic Authentication Flow

Browser Requests Protected Resource

            |

            v

       Server Challenge

            |

            v

     Authentication Required

            |

            v

       Provide Credentials

            |

            v

       Server Validates

            |

       +----+----+

       |         |

     Valid     Invalid

       |         |

       v         v

 Access       Access

 Granted      Denied


12. Selenium 4 Authentication Handling

Selenium 4 introduced improved support for authentication scenarios through its newer browser/network capabilities. Selenium's authentication functionality can register credentials for authentication challenges rather than requiring credentials to be embedded directly in the navigation URL.

Modern Selenium documentation also provides WebDriver BiDi network authentication handlers for authentication-required events. This allows an automation framework to respond to authentication challenges programmatically.


13. Authentication Using Selenium's HasAuthentication

In Selenium Java, authentication can be registered through the HasAuthentication interface for supported authentication scenarios.

import org.openqa.selenium.HasAuthentication;

import org.openqa.selenium.UsernameAndPassword;

import org.openqa.selenium.WebDriver;

 

HasAuthentication authentication =

        (HasAuthentication) driver;

 

authentication.register(

        () -> new UsernameAndPassword(

                "username",

                "password"

        )

);

After registering the credentials, the driver can use them when an applicable authentication challenge occurs.


14. Registering Authentication for a Specific Site

Authentication credentials can also be associated with a specific site or URI condition.

HasAuthentication authentication =

        (HasAuthentication) driver;

 

authentication.register(

        uri -> uri.getHost().contains("example.com"),

        new UsernameAndPassword(

                "username",

                "password"

        )

);

This approach is useful when a test framework interacts with multiple domains and different credentials are required for different protected resources.


15. Basic Authentication with URL Credentials

A traditional technique for HTTP Basic Authentication is placing the username and password in the URL.

driver.get(

    "https://username:[email protected]"

);

Although this technique is simple, embedding credentials in URLs can expose sensitive information through browser history, logs, screenshots, or other tooling. Therefore, it should not be the preferred approach for sensitive credentials.


16. Why URL Credentials Should Be Used Carefully

  • Credentials may appear in logs.
  • Credentials may appear in browser history.
  • Credentials may be captured by debugging tools.
  • Credentials can accidentally enter CI/CD logs.
  • Credentials may be exposed when URLs are copied.
  • Security policies may prohibit credentials in URLs.

For modern automation frameworks, authentication handlers or secure authentication mechanisms are generally preferable when supported.


17. Authentication with Selenium WebDriver BiDi

WebDriver BiDi provides network capabilities that can intercept authentication-required events and supply credentials programmatically. This is useful for browser automation scenarios involving Basic Authentication and similar authentication challenges.

Authentication Request

        |

        v

WebDriver BiDi Network

        |

        v

Authentication Handler

        |

        v

Provide Credentials

        |

        v

Protected Resource


18. Java Authentication Handler Concept

The exact API available depends on the Selenium version and driver implementation. A typical modern Selenium Java approach uses the BiDi network module to intercept authentication-required requests and continue the request with credentials.

Network network = new Network(driver);

 

network.addIntercept(

        new AddInterceptParameters(

                InterceptPhase.AUTH_REQUIRED

        )

);

 

network.onAuthRequired(

        responseDetails ->

            network.continueWithAuth(

                responseDetails

                    .getRequest()

                    .getRequestId(),

                new UsernameAndPassword(

                    "username",

                    "password"

                )

            )

);


19. Validating Successful Authentication

Providing credentials is only one part of authentication testing. The test should also verify that authentication actually succeeded.

Common validation methods include:

  • Checking the page title.
  • Checking the current URL.
  • Checking for a dashboard element.
  • Checking for a logout button.
  • Checking authenticated user information.
  • Checking a success message.
  • Checking access to a protected resource.

Assert.assertTrue(

    driver.findElement(

        By.id("dashboard")

    ).isDisplayed()

);


20. Validating Login Using URL

String currentUrl = driver.getCurrentUrl();

 

Assert.assertTrue(

        currentUrl.contains("/dashboard")

);

URL validation can be useful, but it should be combined with an application-specific UI assertion when possible.


21. Validating Authentication Using Logout Button

boolean logoutVisible =

        driver.findElement(

            By.id("logout")

        ).isDisplayed();

 

Assert.assertTrue(

        logoutVisible,

        "Logout button should be visible"

);

A visible logout control is often a useful indication that the user is authenticated.


22. Invalid Authentication Testing

Authentication testing should not only verify valid credentials. Negative scenarios should also be tested.

@Test

public void invalidLoginTest() {

 

    loginPage.login(

            "invalidUser",

            "wrongPassword"

    );

 

    String errorMessage =

            driver.findElement(

                By.id("error")

            ).getText();

 

    Assert.assertEquals(

            errorMessage,

            "Invalid credentials"

    );

}


23. Empty Username and Password

Required-field validation is another important authentication scenario.

@Test

public void emptyCredentialsTest() {

 

    loginPage.login("", "");

 

    String message =

            driver.findElement(

                By.id("validationMessage")

            ).getText();

 

    Assert.assertTrue(

            message.contains("required")

    );

}


24. Data-Driven Authentication Testing

TestNG Data Providers can be used to test multiple authentication combinations.

@DataProvider(name = "loginData")

public Object[][] loginData() {

    return new Object[][] {

        {"admin", "admin123", true},

        {"manager", "manager123", true},

        {"invalid", "wrong123", false},

        {"", "", false}

    };

}

 

@Test(dataProvider = "loginData")

public void loginTest(

        String username,

        String password,

        boolean expectedSuccess) {

 

    System.out.println(

            username + " : " + expectedSuccess

    );

}


25. Authentication Testing with Different User Roles

Applications often support multiple roles. Authentication tests can verify that each role can authenticate and access the correct area of the application.

RoleExample Access
AdminAdministration area
ManagerReports and management features
EmployeeEmployee dashboard
CustomerCustomer account area


26. Role-Based Authentication Data Provider

@DataProvider(name = "roles")

public Object[][] roles() {

    return new Object[][] {

        {"admin", "admin123", "Admin Dashboard"},

        {"manager", "manager123", "Manager Dashboard"},

        {"employee", "employee123", "Employee Dashboard"}

    };

}

 

@Test(dataProvider = "roles")

public void roleLoginTest(

        String username,

        String password,

        String expectedDashboard) {

 

    loginPage.login(username, password);

 

    Assert.assertTrue(

        driver.getTitle().contains(expectedDashboard)

    );

}


27. Session-Based Authentication

After successful authentication, many web applications create an authenticated session. The session may be represented through cookies or other browser-managed state.

Login

  |

  v

Server Validates Credentials

  |

  v

Session Created

  |

  v

Session Identifier Stored

  |

  v

Protected Requests Use Session

  |

  v

Authenticated User


28. Working with Cookies

Selenium provides cookie APIs that can be useful when a test needs to inspect or manipulate browser session state.

Cookie cookie =

        driver.manage()

              .getCookieNamed("session");

 

System.out.println(

        cookie.getValue()

);

Cookie manipulation should only be used when it is appropriate for the application's authentication architecture and the test's purpose.


29. Adding an Authentication Cookie

Cookie sessionCookie =

        new Cookie(

            "session",

            "sample-session-value"

        );

 

driver.manage().addCookie(

        sessionCookie

);

 

driver.navigate().refresh();

Real applications may use signed, encrypted, short-lived, or server-side session mechanisms, so a manually created cookie may not be sufficient for authentication.


30. Token-Based Authentication

Some applications use tokens to represent authenticated sessions. Common examples include access tokens and bearer tokens.

User Credentials

      |

      v

Authentication Server

      |

      v

Access Token

      |

      v

Protected Resource

When testing token-based systems, the token should be handled securely and should not be exposed unnecessarily in source code, logs, screenshots, or reports.


31. Authentication and APIs

In modern automation projects, UI tests may depend on API authentication. For example, an API can be used to create a test user or prepare test data before Selenium opens the browser.

API Authentication

       |

       v

Create Test User

       |

       v

Prepare Test Data

       |

       v

Open Browser

       |

       v

Selenium UI Test


32. Authentication Through Pre-Authenticated State

For large test suites, repeatedly performing a complete login flow can increase execution time. Depending on the application architecture, teams may use a controlled pre-authenticated state or reusable session setup.

This should be designed carefully so that tests do not accidentally share mutable authentication state.


33. Authentication and Page Object Model

Authentication should be encapsulated inside reusable Page Objects or authentication components whenever possible.

Test Class

    |

    v

LoginPage

    |

    v

Authentication Method

    |

    v

Application Login

    |

    v

DashboardPage

This design prevents authentication locators and actions from being duplicated throughout the test suite.


34. Authentication Component Example

public class AuthenticationPage {

 

    private final WebDriver driver;

 

    private final By username =

            By.id("username");

 

    private final By password =

            By.id("password");

 

    private final By loginButton =

            By.id("loginButton");

 

    public AuthenticationPage(

            WebDriver driver) {

        this.driver = driver;

    }

 

    public void authenticate(

            String user,

            String pass) {

 

        driver.findElement(username)

                .sendKeys(user);

 

        driver.findElement(password)

                .sendKeys(pass);

 

        driver.findElement(loginButton)

                .click();

    }

}


35. Authentication with Explicit Wait

Authentication often involves redirects, asynchronous requests, and dynamically loaded dashboards. Explicit waits can help synchronize the test with the application.

WebDriverWait wait =

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10)

        );

 

wait.until(

    ExpectedConditions.visibilityOfElementLocated(

        By.id("dashboard")

    )

);


36. Why Waits Matter During Authentication

  • Login requests may take time to complete.
  • Redirects may occur after login.
  • Dashboard elements may load asynchronously.
  • Authentication tokens may be processed asynchronously.
  • Immediately checking elements can cause synchronization failures.


37. Authentication Timeout Handling

Authentication requests can fail because of network delays, invalid credentials, server errors, or expired sessions. Tests should provide useful failure information.

try {

 

    wait.until(

        ExpectedConditions.visibilityOfElementLocated(

            By.id("dashboard")

        )

    );

 

} catch (TimeoutException e) {

 

    System.out.println(

        "Authentication may have failed"

    );

 

    throw e;

}


38. Handling Authentication Redirects

Some applications redirect users after successful authentication.

Login Page

   |

   v

Submit Credentials

   |

   v

Authentication Server

   |

   v

Redirect

   |

   v

Dashboard

Tests should wait for a stable post-login condition instead of relying only on a fixed sleep.


39. Authentication with TestNG Configuration

TestNG configuration methods can be used to prepare authentication before individual tests.

@BeforeMethod

public void authenticateUser() {

 

    driver = new ChromeDriver();

 

    driver.get(

        "https://example.com/login"

    );

 

    LoginPage loginPage =

        new LoginPage(driver);

 

    loginPage.login(

        "testuser",

        "testpassword"

    );

}


40. Authentication in BaseTest

Large Selenium frameworks commonly use a BaseTest class for common browser and authentication setup.

public class BaseTest {

 

    protected WebDriver driver;

 

    @BeforeMethod

    public void setup() {

 

        driver = new ChromeDriver();

 

        driver.manage()

              .window()

              .maximize();

    }

 

    protected void login() {

 

        driver.get(

            "https://example.com/login"

        );

 

        LoginPage loginPage =

            new LoginPage(driver);

 

        loginPage.login(

            "testuser",

            "testpassword"

        );

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


41. Authentication and Test Isolation

Each test should ideally have a predictable authentication state. Sharing authentication state between unrelated tests can create test-order dependencies.

Test 1

  |

  +-- Login

  +-- Test

  +-- Logout

 

Test 2

  |

  +-- Login

  +-- Test

  +-- Logout


42. Authentication and Parallel Execution

When authentication tests execute in parallel, each test should use isolated browser sessions and appropriate credentials.

Thread 1

   |

   +-- Driver 1

   +-- User A

   +-- Session A

 

Thread 2

   |

   +-- Driver 2

   +-- User B

   +-- Session B

Sharing one WebDriver instance or one mutable authentication session between concurrent tests can cause interference.


43. Thread-Safe Driver Management

A parallel Selenium framework can use a thread-local WebDriver strategy so that each test thread receives its own browser session.

private static ThreadLocal<WebDriver> driver =

        new ThreadLocal<>();

 

public static void setDriver(

        WebDriver webDriver) {

 

    driver.set(webDriver);

}

 

public static WebDriver getDriver() {

    return driver.get();

}

 

public static void unload() {

    driver.remove();

}


44. Authentication with Multiple Environments

Authentication credentials and URLs may differ between QA, staging, and other environments.

@DataProvider(name = "environments")

public Object[][] environments() {

    return new Object[][] {

        {

            "QA",

            "https://qa.example.com",

            "qaUser"

        },

        {

            "Stage",

            "https://stage.example.com",

            "stageUser"

        }

    };

}

Environment-specific secrets should be obtained through secure configuration rather than being committed as plain text.


45. Authentication with Configuration Files

Non-sensitive configuration values can be stored in configuration files such as properties files.

browser=chrome

baseUrl=https://qa.example.com

username=testuser

Sensitive credentials should preferably come from secure environment variables or an appropriate secret-management mechanism.


46. Environment Variables for Credentials

Environment variables can prevent credentials from being written directly into test source code.

String username =

        System.getenv("TEST_USERNAME");

 

String password =

        System.getenv("TEST_PASSWORD");

The exact secret-management approach should follow the security practices of the project and CI/CD environment.


47. Authentication and CI/CD

Authentication tests are commonly executed in CI/CD environments. Credentials should be supplied securely by the pipeline rather than committed to the repository.

Developer Commit

      |

      v

CI Pipeline

      |

      v

Build

      |

      v

Secure Test Credentials

      |

      v

Selenium Tests

      |

      v

Authentication

      |

      v

Test Results

      |

      v

Reports


48. Authentication and Jenkins

Jenkins or another CI platform can provide credentials to the test execution environment. The test framework can then retrieve them without storing the secret directly in the Java source code.

Jenkins

   |

   v

Credential Store

   |

   v

Environment Variables

   |

   v

TestNG

   |

   v

Selenium

   |

   v

Application


49. Handling Expired Sessions

Authenticated sessions may expire after a period of inactivity or according to application security rules.

A useful test scenario is to verify that an expired session redirects the user to the login page or otherwise requires re-authentication.

Authenticated Session

        |

        v

Session Expires

        |

        v

Open Protected Page

        |

        v

Authentication Required

        |

        v

Login Page


50. Testing Logout

Authentication testing should also verify that logout correctly ends the authenticated session.

@Test

public void logoutTest() {

 

    loginPage.login(

        "testuser",

        "testpassword"

    );

 

    dashboardPage.clickLogout();

 

    Assert.assertTrue(

        driver.getCurrentUrl()

              .contains("/login")

    );

}


51. Testing Session Security Behavior

A logout test can be extended by attempting to access a protected page after logout and verifying that authentication is required again.

Login

  |

  v

Dashboard

  |

  v

Logout

  |

  v

Open Protected URL

  |

  v

Login Required


52. Authentication with Cookies After Logout

Depending on the application's implementation, logout may invalidate the server-side session, remove authentication cookies, or perform other session invalidation operations.

Selenium tests should validate the user-visible security behavior rather than assuming a particular internal implementation.


53. Multi-Factor Authentication

Multi-Factor Authentication (MFA) requires more than one verification factor. Examples include a password plus an OTP, authentication application code, hardware security key, or another verification mechanism.

Automating MFA requires a test strategy that is agreed upon with the application's development and security teams. Common approaches include dedicated test accounts, controlled test OTP mechanisms, or test-environment-specific authentication flows.


54. OTP Authentication Testing

For test environments, an OTP may be generated by a controlled test service or retrieved from an approved test data source.

Enter Username

      |

      v

Enter Password

      |

      v

Request OTP

      |

      v

Retrieve Test OTP

      |

      v

Enter OTP

      |

      v

Authenticated

Real production OTPs should not be bypassed or exposed merely for automation convenience.


55. OAuth Authentication

OAuth-based applications often involve redirects between the application and an authorization server. Selenium can automate portions of a permitted authentication flow, but complex identity-provider interactions may require a dedicated test strategy.

Application

    |

    v

Authorization Server

    |

    v

User Authentication

    |

    v

Authorization

    |

    v

Redirect to Application

    |

    v

Authenticated Session


56. SSO Authentication

Single Sign-On (SSO) allows users to authenticate through a centralized identity provider and access multiple applications.

For automated testing, teams commonly use dedicated test identities and controlled test environments rather than attempting to automate personal or production identity-provider accounts.


57. Authentication Failure Scenarios

ScenarioExpected Behavior
Invalid usernameAuthentication rejected
Invalid passwordAuthentication rejected
Empty credentialsValidation displayed
Expired passwordPassword-expiration workflow
Locked accountAccount-lock message
Expired sessionLogin required again
Unauthorized roleAccess denied
Invalid authentication challengeProtected resource remains inaccessible


58. Handling Account Lockout Tests

Applications may temporarily lock an account after repeated unsuccessful authentication attempts. Automated tests should use dedicated test accounts and carefully controlled data to avoid unintentionally locking shared accounts.

Invalid Attempt

      |

      v

Invalid Attempt

      |

      v

Invalid Attempt

      |

      v

Account Lock

      |

      v

Verify Lock Message


59. Authentication Error Messages

Error messages should be validated when authentication fails.

String error =

        driver.findElement(

            By.cssSelector(".login-error")

        ).getText();

 

Assert.assertEquals(

        error,

        "Invalid username or password"

);


60. Authentication and Screenshots

Screenshots are useful when authentication tests fail. However, screenshots must be reviewed carefully because they may accidentally expose usernames, tokens, personal information, or other sensitive data.

Authentication Failure

        |

        v

Capture Screenshot

        |

        v

Attach to Report

        |

        v

Review Sensitive Data Exposure


61. Authentication and Test Reports

Test reports should identify authentication-related failures clearly without exposing passwords, tokens, cookies, or other secrets.

For example, a report may safely contain:

Test: Valid Login

User Type: Admin

Result: PASS

Instead of exposing:

Username: admin

Password: admin123


62. Masking Sensitive Information

When authentication data is logged, sensitive values should be masked.

System.out.println(

    "Username: " + username

);

 

System.out.println(

    "Password: ********"

);

The goal is to keep debugging information useful without revealing authentication secrets.


63. Authentication Utility Class

A reusable authentication utility can centralize common login operations.

public class AuthenticationUtil {

 

    public static void login(

            WebDriver driver,

            String username,

            String password) {

 

        driver.findElement(

            By.id("username")

        ).sendKeys(username);

 

        driver.findElement(

            By.id("password")

        ).sendKeys(password);

 

        driver.findElement(

            By.id("loginButton")

        ).click();

    }

}


64. Reusable Authentication Service

In larger frameworks, authentication can be separated into an authentication service that manages login, logout, session preparation, and authentication validation.

AuthenticationService

        |

        +-- login()

        |

        +-- logout()

        |

        +-- isAuthenticated()

        |

        +-- validateSession()

        |

        +-- refreshSession()


65. Authentication Framework Architecture

                 TestNG Tests

                      |

                      v

              Authentication Layer

                      |

          +-----------+-----------+

          |                       |

     Form Login              HTTP Auth

          |                       |

          v                       v

      LoginPage             Auth Handler

          |                       |

          +-----------+-----------+

                      |

                      v

                WebDriver

                      |

                      v

                 Application

                      |

                      v

                Assertions

                      |

                      v

                 Reports


66. Complete Authentication Example

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.ExpectedConditions;

import org.openqa.selenium.support.ui.WebDriverWait;

 

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class AuthenticationTest {

 

    private WebDriver driver;

    private WebDriverWait wait;

 

    @BeforeMethod

    public void setup() {

 

        driver = new ChromeDriver();

 

        driver.manage()

                .window()

                .maximize();

 

        wait = new WebDriverWait(

                driver,

                Duration.ofSeconds(10)

        );

 

        driver.get(

                "https://example.com/login"

        );

    }

 

    @Test

    public void validAuthenticationTest() {

 

        driver.findElement(

                By.id("username")

        ).sendKeys("testuser");

 

        driver.findElement(

                By.id("password")

        ).sendKeys("testpassword");

 

        driver.findElement(

                By.id("loginButton")

        ).click();

 

        wait.until(

                ExpectedConditions.visibilityOfElementLocated(

                        By.id("dashboard")

                )

        );

 

        Assert.assertTrue(

                driver.findElement(

                        By.id("dashboard")

                ).isDisplayed()

        );

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


67. Authentication Test Project Structure

src

|-- test

    |-- java

        |-- base

        |   |-- BaseTest.java

        |

        |-- pages

        |   |-- LoginPage.java

        |   |-- DashboardPage.java

        |

        |-- tests

        |   |-- LoginTest.java

        |   |-- LogoutTest.java

        |   |-- SessionTest.java

        |

        |-- utilities

        |   |-- AuthenticationUtil.java

        |   |-- DriverFactory.java

        |   |-- ConfigReader.java

        |

        |-- data

            |-- LoginDataProvider.java


68. Authentication Testing Flow in a Framework

TestNG

  |

  v

BaseTest

  |

  v

Driver Initialization

  |

  v

Authentication Service

  |

  v

Login Page / Auth Handler

  |

  v

Authenticated Session

  |

  v

Page Object

  |

  v

Test Case

  |

  v

Assertion

  |

  v

Report


69. Common Authentication Handling Mistakes

  • Trying to locate browser-level authentication dialogs with normal DOM locators.
  • Hard-coding passwords in source code.
  • Putting sensitive credentials into URLs.
  • Printing passwords in console logs.
  • Including passwords in test reports.
  • Sharing authentication sessions between parallel tests.
  • Using personal accounts for automated testing.
  • Ignoring session expiration.
  • Not testing invalid credentials.
  • Not validating that authentication actually succeeded.
  • Using fixed sleeps instead of appropriate waits.
  • Failing to clean up browser sessions.


70. Best Practices for Authentication Handling

  • Use dedicated test accounts.
  • Keep authentication logic reusable.
  • Use Page Object Model for form-based login.
  • Use modern Selenium authentication/network capabilities where appropriate.
  • Avoid exposing credentials in URLs.
  • Do not hard-code production credentials.
  • Use secure environment variables or secret-management solutions.
  • Mask sensitive information in logs.
  • Do not include passwords or tokens in reports.
  • Use explicit waits for post-login conditions.
  • Validate successful authentication explicitly.
  • Test invalid credentials and logout behavior.
  • Keep parallel authentication sessions isolated.
  • Use dedicated environments for automation.
  • Clean up browser sessions after tests.


71. Authentication Handling vs Normal Login Automation

FeatureNormal LoginBrowser/HTTP Authentication
UI FormUsually availableMay not be available
Selenium LocatorsUsually applicableNot directly applicable to browser-level prompt
Username FieldHTML elementMay be browser/network controlled
Password FieldHTML elementMay be browser/network controlled
Typical StrategyPage Object + locatorsAuthentication/network handler


72. Authentication Handling vs Authorization Testing

Authentication TestingAuthorization Testing
Checks identity verificationChecks permission enforcement
Tests login credentialsTests role permissions
Example: valid passwordExample: employee cannot access admin page
Focuses on identityFocuses on access control


73. Practical Authentication Test Scenarios

  1. Verify login with valid credentials.
  2. Verify login with invalid username.
  3. Verify login with invalid password.
  4. Verify login with empty username.
  5. Verify login with empty password.
  6. Verify login with both fields empty.
  7. Verify password masking.
  8. Verify successful redirection after login.
  9. Verify authenticated dashboard.
  10. Verify logout.
  11. Verify protected-page access after logout.
  12. Verify session expiration.
  13. Verify account lock behavior.
  14. Verify role-based access.
  15. Verify authentication error messages.
  16. Verify Basic Authentication where applicable.
  17. Verify authentication across supported browsers.
  18. Verify authentication in CI/CD.
  19. Verify authentication with multiple environments.
  20. Verify sensitive data is not exposed in reports.


74. Practical Exercise 1: Login Authentication

  1. Create a Selenium WebDriver test.
  2. Open the login page.
  3. Enter a valid username.
  4. Enter a valid password.
  5. Click Login.
  6. Wait for the dashboard.
  7. Assert that the dashboard is displayed.
  8. Logout.
  9. Verify that the login page is displayed again.


75. Practical Exercise 2: Negative Authentication

  1. Create invalid username and password test data.
  2. Use a TestNG Data Provider.
  3. Execute the same login method for multiple invalid combinations.
  4. Capture the authentication error message.
  5. Assert the expected result.


76. Practical Exercise 3: Role-Based Authentication

  1. Create Admin test credentials.
  2. Create Manager test credentials.
  3. Create Employee test credentials.
  4. Authenticate each user.
  5. Verify the correct dashboard.
  6. Verify restricted functionality.
  7. Logout after each test.


77. Practical Exercise 4: Basic Authentication

  1. Identify a dedicated test environment protected by HTTP Basic Authentication.
  2. Configure Selenium authentication handling.
  3. Navigate to the protected resource.
  4. Provide credentials through the supported authentication mechanism.
  5. Verify successful access.
  6. Verify behavior with invalid credentials.


78. Quick Reference Table

ConceptPurpose
AuthenticationVerifies user identity
AuthorizationControls access permissions
Form LoginAutomates HTML login forms
Basic AuthenticationHandles HTTP authentication challenges
HasAuthenticationSelenium authentication capability
WebDriver BiDiProvides modern browser/network capabilities
CookieCan represent browser session state
TokenCan represent authenticated access
POMEncapsulates login interaction
DataProviderSupports multiple authentication test data sets
Explicit WaitSynchronizes tests with authentication results
Environment VariablesCan provide credentials without hard-coding them


79. Interview Questions on Authentication Handling

1. What is authentication?

Authentication is the process of verifying the identity of a user or system before granting access to a protected resource.

2. What is the difference between authentication and authorization?

Authentication verifies identity, while authorization determines what an authenticated identity is permitted to access.

3. How do you automate a normal login page in Selenium?

Use Selenium locators to identify the username and password fields, enter the credentials, click the login button, and verify the authenticated state.

4. Can Selenium handle HTTP Basic Authentication?

Yes. Modern Selenium provides authentication-related capabilities and network handling mechanisms for supported authentication scenarios.

5. Why can't normal findElement() always handle an authentication popup?

Because a browser-level authentication prompt may not be an HTML element in the page DOM.

6. What is HasAuthentication?

HasAuthentication is a Selenium capability/interface that can be used to register authentication credentials for applicable authentication challenges.

7. What is WebDriver BiDi?

WebDriver BiDi is a bidirectional browser automation protocol that enables Selenium to interact with browser events and capabilities, including network-related functionality.

8. What is Basic Authentication?

HTTP Basic Authentication is an HTTP authentication mechanism where a protected resource challenges the client for credentials.

9. Should credentials be passed in the URL?

Credentials in URLs should be avoided for sensitive automation because they can be exposed through logs, history, or other tooling.

10. How can credentials be stored securely?

Credentials can be supplied through environment variables, CI/CD credential stores, or approved secret-management systems.

11. How do you test invalid login?

Provide invalid credentials and verify the expected authentication error or rejection behavior.

12. How do you verify successful authentication?

Verify a stable post-login condition such as a dashboard element, expected URL, page title, or logout control.

13. How can DataProvider help authentication testing?

It can supply multiple username, password, role, and expected-result combinations to a single test method.

14. How do you handle authentication in Page Object Model?

Create a LoginPage or AuthenticationPage containing authentication locators and actions, then call it from test classes.

15. How do you handle authentication in parallel tests?

Each concurrent test should use an isolated WebDriver and appropriate session and credential data.

16. What is session-based authentication?

It is an authentication model where the server establishes an authenticated session that subsequent requests use to identify the user.

17. What is token-based authentication?

It uses an access token or similar credential to represent authenticated access to protected resources.

18. What is MFA?

Multi-Factor Authentication requires more than one authentication factor.

19. Why should authentication failures include useful diagnostics?

Useful diagnostics help identify whether the problem occurred during credential submission, authentication, redirection, synchronization, or application loading.

20. What is the most important security practice in automated authentication?

Do not unnecessarily expose passwords, tokens, cookies, or other sensitive authentication information in source code, URLs, logs, screenshots, or reports.


80. Learning Roadmap for Authentication Handling

  1. Understand authentication and authorization.
  2. Learn normal HTML form-based login automation.
  3. Learn Page Object Model for login pages.
  4. Learn TestNG authentication tests.
  5. Learn positive and negative authentication scenarios.
  6. Learn DataProvider-based credential testing.
  7. Learn cookie and session concepts.
  8. Understand token-based authentication.
  9. Understand HTTP Basic Authentication.
  10. Learn Selenium authentication capabilities.
  11. Learn Selenium WebDriver BiDi network authentication concepts.
  12. Learn environment-based configuration.
  13. Learn secure credential management.
  14. Learn authentication testing in CI/CD.
  15. Learn parallel authentication testing.
  16. Build a reusable authentication framework.


81. Summary

Authentication Handling is an essential part of Selenium automation because most real-world applications protect important functionality behind authentication.

For normal HTML login forms, Selenium can interact directly with username, password, and login elements. Page Object Model provides a maintainable way to encapsulate these interactions.

HTTP Basic Authentication is different because the authentication challenge may occur outside the normal page DOM. Modern Selenium provides authentication and network capabilities that can be used to respond to supported authentication challenges programmatically.

Authentication tests should cover successful login, invalid credentials, logout, session expiration, role-based access, protected resources, and authentication failure scenarios.

Security is also important. Credentials should not be unnecessarily hard-coded, placed in URLs, printed in logs, or included in test reports. Dedicated test accounts and secure credential-management mechanisms should be used for automation.

For scalable Selenium frameworks, authentication can be integrated with Page Object Model, TestNG Data Providers, reusable authentication services, WebDriver management, CI/CD, reporting, and parallel execution.


82. Course Resources

Learn more about Selenium WebDriver and automation testing:

Final Takeaway: Authentication handling allows Selenium automation frameworks to reliably test protected web applications while keeping authentication logic reusable, test sessions isolated, and sensitive credentials protected.

whatsapp