0

I'm using Django, and am looking to have the option to login both using a web page (the standard way) and through a separate client process (for the sake of my testing, using python requests)

I've seen another answer about doing an ajax login, but my understanding of this solution is that it would be vulnerable to a CSRF attack, as it's only taking the POSTed username/password.

What I'd like to do is request a CSRF token (with a GET call to my custom /auth-api/login view), and then pass this in a POST call along with the username and password.

This is what I currently have in views.py

from django.middleware import csrf
from django.http import JsonResponse

def login( request ) :
    return JsonResponse( { 'csrf_token': csrf.get_token( request ) } )

From Python on the client end, I'm then doing: (I have verify=False here because I am currently using a self-signed SSL certificate for development purposes)

result = s.get( "https://<ip_addr>/auth-api/login", verify = False )
csrf_token = json.loads( result.text )['csrf_token']

s.post( "https://<ip_addr>/auth-api/login",
         verify = False,
         data = { 'csrfmiddlewaretoken': csrf_token,
                  'username': "<username>",
                  'password': "<password>" },
         cookies = dict( result.cookies ),
         headers = { 'X-CSRFToken': res.cookies['csrftoken'] } )

However, the text of the response to this tells me that the CSRF token is missing or incorrect. I am passing it in 3 places (the POST data, cookies and headers).

Am I missing something simple here, or should I be taking a different approach to this api kind of login?

Hugh
  • 726
  • 1
  • 6
  • 25
  • The view does not have to care about the CSRF token, the middleware will already check that. – Willem Van Onsem Jul 27 '19 at 17:52
  • Don't I still need to include the 'csrfmiddlewaretoken' field in my POST response, though? And if so, where do I get this from? – Hugh Jul 27 '19 at 18:03

0 Answers0