Jeril
Jeril

Reputation: 8521

Python - passing csrf token with requests to a node.js server

I want trying to login to node.js server using csrf token, but it is not working and I am confused which csrf token to consider.

The following is the cookie information:

>>> client.cookies
<RequestsCookieJar[
    Cookie(version=0, name='user.sid', value='s%3Ay-JiI_2cPs0jsnVb_g_KJCU-k9GrGISm.O6SSmsVEMmTzaTWM7btqaZZGUs2WvkZTDc9VfaWlikE', port=None, port_specified=False, domain='.domain.dev', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False), 
    Cookie(version=0, name='_csrf', value='s%3Ax00MKKqyFl9NHpg-3DVDaUkK.dVDwbGnXl6JGSPP3GrvVe17cYpcZNMX0RrJ8lzSGSHE', port=None, port_specified=False, domain='subdomain.domain.dev', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False),
    Cookie(version=0, name='_csrfToken', value='18vLBP1L-gaiBFbycylW7475Pyu8HtizLNoA', port=None, port_specified=False, domain='subdomain.domain.dev', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)
]>

There are two csrf tokens and one user.sid. The following was the code that I tries:

import requests

URL = 'https://subdomain.domain.dev/login'

client = requests.session()

# Retrieve the CSRF token first
client.get(URL, verify=False)  # sets cookie
csrftoken = client.cookies['_csrf']
# csrftoken = client.cookies['_csrfToken']
login_data = dict(
    username=EMAIL,
    password=PASSWORD,
    csrfmiddlewaretoken=csrftoken,
    next='/'
)
r = client.post(
    URL,
    data=login_data,
    headers=dict(Referer=URL)
)

I am getting 500 Error, I tried with both the tokens.

How should I send a POST request for the mentioned cookie. Kindly help. Thanks

Upvotes: 0

Views: 1146

Answers (1)

Safvan CK
Safvan CK

Reputation: 1340

import sys
import requests

URL = 'https://xxx.xxxxxxx.xxx/xxxx'

client = requests.session()

# Retrieve the CSRF token first
client.get(URL)  # sets cookie
if 'csrftoken' in client.cookies:
    csrftoken = client.cookies['csrftoken']
else:
    csrftoken = client.cookies['csrf']

login_data = dict(username=EMAIL, password=PASSWORD, csrfmiddlewaretoken=csrftoken, next='/')
r = client.post(URL, data=login_data, headers=dict(Referer=URL))

While using http(unsecured), the Referer header is often filtered out and otherwise easily spoofable anyway, so most sites no longer require the header to be set. However, when using an SSL connection and if it is set, it does make sense for the site to validate that it at least references something that could logically have initiated the request.

Upvotes: 1

Related Questions