0

I have a Django restful API (using django-rest-framework) where the POST requests require prior authentication. I would like to populate the database by sending data to the API, however, I cannot figure out how to do the authentication programmatically. I tried requests, pycurl and httplib2 so far:

import httplib2
from urllib.parse import urlencode

h = httplib2.Http(".cache")

h.add_credentials(username, password)

headers = {'Content-type': 'application/x-www-form-urlencoded'}

data = {
    "label": "SA2",
    "flagged": "false",
    "notes": ""
}

resp, content = h.request(
    "https://example.com/api/data", "POST", urlencode(data), headers=headers
)

resp
>>>
{
 'server': 'nginx/1.18.0 (Ubuntu)', 
 'date': 'Sat, 05 Mar 2022 00:06:32 GMT', 
 'content-type': 'text/html', 
 'transfer-encoding': 'chunked', 
 'connection': 'keep-alive', 
 'cross-origin-opener-policy': 'same-origin', 
 'referrer-policy': 'same-origin', 
 'vary': 'Origin', 
 'x-content-type-options': 'nosniff', 
 'x-frame-options': 'DENY', 
 'status': '403', 
 'content-length': '1867', 
 '-content-encoding': 'gzip'
}

content
>>>
b'{"detail":"Authentication credentials were not provided."}'

In the browser, I first have to visit the login page. Then the website sends a CRFT token. Here is a solution using curl and bash. I prefer to use Python.

Soerendip
  • 7,684
  • 15
  • 61
  • 128

1 Answers1

1

You need to provide the credentials in the header.

import base64

# ...
username="<username>"
password="<password>"
credentials=username + ":" + password

encoded_credentials = base64.b64encode(credentials.encode()).decode()
headers["Authorization"] = "Basic " + encoded_credentials

# ...

https://www.ibm.com/docs/en/ibm-mq/9.0?topic=security-using-http-basic-authentication-rest-api

Kyell
  • 621
  • 5
  • 9