Bad CSRF on request from cloned session with Python

AI-generated summary

Bad CSRF on Request from Cloned Session with Python

Hans is attempting to clone a Discourse forum user’s session cookies using Python and perform actions like liking posts. Although the cloned session successfully retrieves pages, including private categories, it fails to generate a CSRF token when making a POST request, resulting in a “Bad CSRF” error. Hans wants to know why CSRF tokens are generated in the browser but not in the cloned session and how to obtain a CSRF token for the request.

blake suggested using an API key, especially since the tool is initially intended for moderation purposes. However, Hans plans to make the tool available to any logged-in user, allowing them to perform actions programmatically using their own session.

I am a moderator on a Discourse forum and I wanted to write a python program that will clone the session cookies out of the browser and run a simple user action like liking a post. I successfully cloned the session and was able to use GET requests to get any page, even private categories (so I know the session has been successfully cloned), but when I tried to simply like a post with a POST request I got “Bad CSRF” and upon investigation I noticed that no CSRF token was being generated in the request. I want to know why CSRF tokens will generate in the browser, but not in this cloned session. Is there a way I can get a CSRF token for the request? My simple code is below.

import requests
import browsercookie

cj = browsercookie.firefox()

r = requests.post("https://somediscoursesite.com/post_actions", data={'id':'theid','post_action_type_id':'2','flag_topic':'false'}, cookies=cj)

print(r.status_code)
print(r.request.headers)

Will this be used by all users, just staff, or just yourself? I guess what I’m getting at if this is just for you to help with moderation it would be best to use an api key or to generate some api keys for specific staff users.

I mean for it to be used by any logged-in user. Basically I want to take the user session and allow the user to perform actions with it programmatically with python, namely, liking posts. I know it would be way easier to use an admin key, but I want it to be available to any user and since a user can like a post in their browser why can’t that be performed programmatically from their own device with a cloned session in command prompt?