Retrieving Access Token with Robot Framework and Python
Image Credit: Freepik

Retrieving Access Token with Robot Framework and Python

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(“https://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 [email protected] 12345

Follow Us For More Updates…

要查看或添加评论,请登录

社区洞察

其他会员也浏览了