Python Forum

Full Version: Getting csrf token to log in
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Running a load test on a web portal (Liferay) using Locust but cannot log in. I am posting the username and password, but need the csrf token. I can inspect the page and see in the response that it is assigning a csrf token as "Liferay.authToken" but have no clue how to grab that. When posting the data to log in, it needs the token (the page calls it p_auth).

Here is a similar fix for this but it's not working for me, maybe because the token is called something different on my page:

Any help would be appreciated!
If it's set in a cookie, then that link should help. If it's a hidden form field (which I think is more common), then you can use beautifulsoup to find it and get the value.
You can try to use Requests with session() to handle cookies.
import requests

url = 'url'
client = requests.session()
# Retrieve the CSRF token first
csrf = client.get(url).cookies['csrftoken']

login_data = dict(username=EMAIL, password=PASSWORD, csrfmiddlewaretoken=csrf, next='/')
r =, data=login_data, headers=dict(Referer=url))

# Check if it worked?
print r.status_code
As mention BeautifulSoup it will be in simelair way,
first set up session(),then search for CSRF token.
import requests
from bs4 import BeautifulSoup

client = requests.Session()
headers = {'User-Agent': 'Mozilla/5.0'}
url = 'url'

soup = BeautifulSoup(client.get(url).text, "html.parser")
csrf = soup.find(name="csrf")
The other way is to be a browser Confused
bye using Selenium/PhantomJS to log in which work fine from Python.
Hi. I've tried the above suggestions but in both cases receive a Max retries exceeded with url error. Reviewing other forum posts about this issue, it doesn't sound like it's an accurate or helpful message but nonetheless, I haven't found a workable solution. I'm trying to write a python script to login to a website via an api.

I'm a novice python script writer so as much detail as possible in your response would be appreciated. Thanks.
Hi appen,

Did you ever find a solution to your problem with the crsf tokens? I have been struggling with what might be the same problem. Please see my post here

snippsat, metlburr said you were the one to talk with -- if you have any advice, please let me know. metlburr attempted to help but said it was outside of his skill set.

Thanks to anyone that can help!