Retrieving Access Token with Robot Framework and Python

Evangelist Apps
Evangelist Apps Blog
2 min readJul 2, 2024
Image source: Freepik

When building test automation for modern web applications, we often need to handle authentication flows to log in and retrieve an access token. This token is then used to make authenticated requests to the application’s APIs during your tests. While this process can be done manually, it’s more efficient to automate it.

In this article, we’ll walk through how to use Robot Framework along with Python and Selenium to log into an application with Auth0 authentication and retrieve the access token from the browser’s localStorage and cookies. This token can then be used for further testing of secured application functionality.

Method:

First, we need to create a custom method using python e.g. access_token.py. Here is the code that needs to be inserted into this method.

from selenium import webdriver

from selenium.webdriver.common.by import By

def perform_login_and_get_token(email, password):

driver = webdriver.Chrome()

driver.implicitly_wait(10)

driver.get(“http://localhost:3000") # Login Page Link

email_box = driver.find_element(By.NAME, “email”)

password_box = driver.find_element(By.NAME, “password”)

auth0_login_button = driver.find_element(By.NAME, “submit”)

email_box.send_keys(“<EMAIL>”)

password_box.send_keys(“<PASSWORD>”)

auth0_login_button.click()

# Grab token from local storage

token = driver.execute_script(“return window.localStorage.getItem(‘access_token’)”)

print(token)

driver.quit()

If the Access token is present in cookies, then run the following code instead of local storage for retrieving the access token from cookies.

# Grab token from cookies

cookies = driver.get_cookies()

token = None

for cookie in cookies:

if cookie[‘name’] == ‘tb_forum_authenticated_prod’:

token = cookie[‘value’]

break

After saving the above code, we need to call this method in our robot code.

Now create a new test using robot framework and run the test.
Example, access_token.robot

Library access_token

Get Access Token

Perform Login And Get Token newtest51@gmail.com 12345

Follow Us For More Updates…

--

--

Evangelist Apps
Evangelist Apps Blog

Evangelist Software is UK based mobile apps development agency that specializes in developing and testing iOS apps.