1

I am sending a POST request to myself:

requests.post("http://localhost:8000/api/", json=data, auth=('myuser', 'mypwd'))

I am using Django to receive the POST request. I want to authenticate that the username and password matches what I have.

def myAPI(request)
    if request.method == 'POST':

          # obtain username and password here

How can I get the username and password in plain text? I've tried request.body.decode(), request.POST.items(), request.META -- just can't find it! I could send the credentials over in data and it would be easy. Alternatively, I can use an API key instead of both username and password, but I wouldn't know how to access that either.

bones225
  • 1,488
  • 2
  • 13
  • 33
  • 1
    It _should be_ in `request.META['HTTP_AUTHORIZATION']` – Selcuk Oct 17 '19 at 03:05
  • 1
    When I do `print('Auth:', request.META['HTTP_AUTHORIZATION'])` it prints something like `Auth: Basic bX85js03jg9sl` (random chars) – bones225 Oct 17 '19 at 03:11
  • Aha -- it was encoded in base64. Found on another [answer](https://stackoverflow.com/questions/38016684/accessing-username-and-password-in-django-request-header-returns-none). – bones225 Oct 17 '19 at 03:15
  • It is not random. It is your username and password, base64 encoded. – Selcuk Oct 17 '19 at 03:16
  • Why is it base64 encoded when all other information is not? – bones225 Oct 17 '19 at 03:17
  • There is a question for that, too: https://stackoverflow.com/questions/13661384/why-base64-in-basic-authentication – Selcuk Oct 17 '19 at 03:26

1 Answers1

0

This will work for you:

req_header = request.META['HTTP_AUTHORIZATION']
credentials = auth_header.split(' ')[1]
base64_decoded_credentials = base64.b64decode(encoded_credentials)
decoded_utf_credentials = base64_decoded_credetials.decode("utf-8").split(':')
username = decoded_utf_credentials[0]
password = decoded_utf_credentials[1]
Deepak K
  • 265
  • 3
  • 7