Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save FrancoisCapon/2838fd6214b937da964fc273b66c4e66 to your computer and use it in GitHub Desktop.
Save FrancoisCapon/2838fd6214b937da964fc273b66c4e66 to your computer and use it in GitHub Desktop.
Properly Update Cookies Value With Python Requests

Properly Update Cookies Value With Python Requests

⚠️ Using http_session.cookies['name'] or http_session.cookies.set('name', 'value') will duplicate the cookie.

🎲 By chance, Requests takes the last created, but it's possible to do it properly by using the domain

📄 class requests.cookies.RequestsCookieJar(policy=None)

import requests
import random
import string

BASE_URL = 'https://domain.tld/'
REGISTER_PATH = 'register'
FLAG_PATH = 'flag'

# register user to get an authentication cookie
username = ''.join(random.choices(string.ascii_lowercase + string.digits, k=10))
registration_data = {'username': username, 'password': username}
http_session = requests.Session()
http_session.post(BASE_URL + REGISTER_PATH, data=registration_data)
# print cookies: one cookie
print(http_session.cookies)

# get cookie domain
# https://github.com/python/cpython/pull/10258
# cookie_domain start with a dot!
cookie_domain = http_session.cookies.list_domains()[0]

# tamper the authentication cookie
cookie_tampered_value = 'tampered_value'
http_session.cookies.set('authentication', cookie_tampered_value, domain=cookie_domain)
# print cookies: still one cookie (no duplication)
print(http_session.cookies)

# get the flag
flag_page = http_session.get(BASE_URL + FLAG_PATH)
print(flag_page.text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment