πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Scenarios
Scenario 78 of 100
Authentication
Advanced

Reusing Authentication Cookies Across Sessions

πŸͺScenario Overview

Reusing Authentication Cookies Across Sessions

Key Takeaways & Cheat Sheet

  • βœ“Perform a single UI login at the start of your test execution suite
  • βœ“Extract active authentication cookies using driver.manage().getCookies()
  • βœ“Save cookies to local file storage formats (like JSON or text)
  • βœ“Inject saved cookies into new driver instances to bypass login screens

Short Direct Answer

To speed up your test suite, perform a single UI login at the start of execution, save the generated cookies to a file, and inject those cookies into new browser instances for subsequent tests. This allows you to bypass the login screen completely and jump straight to the page under test.

⚠️ Senior Warning (Red Flag)

Never reuse cookies without loading the matching domain page first. Trying to add cookies to an uninitialized driver domain throws an InvalidCookieDomainException.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Verify that your cookies are still valid before restoring them. If the cookies have expired, catch the session error and trigger a UI login to refresh the credentials.

SeleniumAutomation.java
Selenium 4 + Java
import org.openqa.selenium.Cookie;
import java.io.*;
import java.util.Set;

public class SessionManager {
    private static File cookieFile = new File("target/session_cookies.data");

    // βœ… Save active cookies to disk
    public static void saveSession(WebDriver driver) throws IOException {
        cookieFile.createNewFile();
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(cookieFile))) {
            oos.writeObject(driver.manage().getCookies());
        }
    }

    // βœ… Inject saved cookies to restore session
    @SuppressWarnings("unchecked")
    public static void restoreSession(WebDriver driver) throws Exception {
        if (!cookieFile.exists()) return;
        
        // Load target domain first to establish context
        driver.get("https://careerraah.com/404");
        
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(cookieFile))) {
            Set<Cookie> cookies = (Set<Cookie>) ois.readObject();
            for (Cookie cookie : cookies) {
                driver.manage().addCookie(cookie);
            }
        }
        // Load target page with active session!
        driver.get("https://careerraah.com/dashboard");
    }
}