Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually get a CSRF token when testing

Tags:

django

I've got a test where I'm checking some authentication behavior. In this test I need to explicitly check CSRF behavior, so I'm using a test client enforce_csrf_checks set to True:

self.csrf_client = Client(enforce_csrf_checks=True)

My question is, what's the simplest way for me to manually get a CSRF token to send with a POST request I'm going to make to that client?

Is the best option to define a custom test view that returns csrf(request), make a request to that view, extract the CSRF token and then use it in the POST request, or is there some easier way I can get a CSRF token to use?

like image 880
Tom Christie Avatar asked Jan 22 '12 20:01

Tom Christie


2 Answers

I know this is an old question, but I stumbled across this while searching for a solution and now I wanted to share my solution in case anyone else has a problem with this.

The CSRF token is indeed stored in the cookie after you login and to access it I had to do the following:

self.client = Client(enforce_csrf_checks=True)
self.client.login(username='temporary', password='temporary')
self.client.get("/url_to_the_form/")
csrf_token = self.client.cookies['csrftoken'].value
like image 76
Daniel Karlsson Avatar answered Oct 08 '22 16:10

Daniel Karlsson


The CSRF token should be getting sent to the client as a cookie (named "csrftoken"). The client is expected to send that cookie back with further requests. Could your Client copy the cookie to where you need it?

like image 29
Mike DeSimone Avatar answered Oct 08 '22 15:10

Mike DeSimone