Search code examples
pythondjangopinaxhttp-requestpython-requests

Received 403 CSRF verification failed when logging through python requests


I use Pinax, and I am trying to perform login test on account project, using requests module.

I did this

def test001_login(self):
    #cookies = {'csrftoken': 'a8356fd05b25fad7004994fd5da89596'}
    r = requests.post(self.loginurl, data={'username':self.username, 'password': self.password}, auth=(self.username, self.password),allow_redirects=True)

    print r.status_code
    print r.text
    print r.cookies

Cookie returned is empty!! With get method, I get a cookie. What is causing this issue?

r.text result:

    <p>Reason given for failure:</p>
    <pre>
    No CSRF or session cookie.
    </pre>

  <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
  <a
  href='http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ref-contrib-csrf'>Django's
  CSRF mechanism</a> has not been used correctly.  For POST forms, you need to
  ensure:</p>

I tried to stick in cookies but it still gave me 403 error.


Solution

  • Your post is not handing the CSRF Token to the login. Does this work:

    r = requests.post(self.loginurl, data={'csrf_token': django.middleware.csrf.get_token(), 'username':self.username, 'password': self.password}, auth=(self.username, self.password),allow_redirects=True)