Search code examples
djangocsrf

How to use django autentication in third-party app?


I'm trying to check authenticate django's user in other app. Actually I run this script:

import requests
import urllib2

main_page = urllib2.urlopen("http://myurl.com/login").read()
csrf = main_page.split("csrfmiddlewaretoken' value='")[1].split("'")[0]


r = requests.post("http://myurl.com/login", data={u'username': u'admin', u'password': u'admin', 'csrfmiddlewaretoken': csrf })

print(r.status_code, r.reason, r.text)

But I getting csrf error. All I want is to check that login parameters that user entered in other app are exists in django's database. How can I do it?

Is there any other ways to use django authentication in third-party apps?


Solution

  • There are most likely better ways to achieve your goal, but to get your code working the way you want, you also need to send the CSRF cookie that Django expects to match up with the token on the page.

    import requests
    
    main_page_request = requests.get("http://127.0.0.1:8000/admin/login/")
    csrf_cookie = main_page_request.cookies.get("csrftoken", "")
    
    r = requests.post("http://127.0.0.1:8000/admin/login/", data={u'username': u'admin', u'password': u'admin', 'csrfmiddlewaretoken': csrf_cookie }, cookies={'csrftoken': csrf_cookie})
    
    print(r.status_code, r.reason, r.text)