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

Maintaining Sessions when Tokens Expire Dynamically

πŸ”„Scenario Overview

Maintaining Sessions when Tokens Expire Dynamically

Key Takeaways & Cheat Sheet

  • βœ“Detect token expiration states (like redirects to login or 401 statuses)
  • βœ“Retrieve fresh token values from background API refresh calls
  • βœ“Execute JS script variables to update local storage web variables
  • βœ“Use browser session storage updates to maintain active states

Short Direct Answer

When testing long workflows, session tokens stored in local storage or cookies can expire. To handle this, implement a verification helper that checks for expiration (e.g. checking for login redirects). If expired, make a fast background API call to refresh the token, and use JavaScript to update the browser's local storage with the new token.

⚠️ Senior Warning (Red Flag)

Avoid hardcoding token expirations or using arbitrary wait loops. If a token expires, catch the redirect to the login page and re-authenticate dynamically to prevent test failures.

πŸ’‘ STAR Deep Dive Explanation & Pro Tip

Updating tokens directly via Javascript is fast and keeps long-running workflows stable without needing to restart the entire test session.

SeleniumAutomation.java
Selenium 4 + Java
// βœ… Dynamic Session Restoration Helper
public void ensureSessionActive() {
    String currentUrl = driver.getCurrentUrl();
    if (currentUrl.contains("/login") || driver.findElements(By.id("session-expired-banner")).size() > 0) {
        System.out.println("Session expired. Refreshing token via API...");
        
        // Retrieve fresh token from backend API
        String freshToken = fetchFreshTokenFromApi();
        
        // Inject token back into browser LocalStorage using JavaScript
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("window.localStorage.setItem('auth_token', arguments[0]);", freshToken);
        
        // Refresh page to apply credentials
        driver.navigate().refresh();
    }
}

private String fetchFreshTokenFromApi() {
    // API request details here
    return "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.newFreshTokenDetails";
}