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 + Javaimport 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");
}
}