'Selenium Python - Auto login with cookie getting domain mismatch error

How to handle auto SSO login with Selenium ? For example, during authentication on www.corportatedomain.com, it redirecting to another domain www.anotherdoamin.com and then it authenticate the user with SSO login. After successful login, it displays desired page. To achieve this type of auto login in Selenium, using below Python scripts, it throws an error - selenium.common.exceptions.InvalidCookieDomainException: Message: invalid cookie domain: Cookie 'domain' mismatch. Is there any solution ?

Chrome version: 97.0.4692.99 Selenium version: 4.1.0 Chrome Webdriver version: latest

import time
import pickle
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

# Capturing cookies
# Comment this code when loading cookies
driver.get("https://www.corportatedomain.com")
time.sleep(10) # Pausing program for user to enter credentials
pickle.dump(driver.get_cookies(), open("cookies.pkl", "wb"))

#Comment this code when capturing cookies
driver.get("https://www.corportatedomain.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source