Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 encode HTTP_AUTHORIZATION headers DRF

I'm trying to create a test using the Django Rest Framework:

self.api = APIClient()
self.api.credentials(HTTP_AUTHORIZATION='client_id ' + str(self.client_id) + ' client_secret ' + str(self.client_secret))
response = self.api.post(url, payload)

But I get this error with the above:

Invalid basic header. Credentials not correctly base64 encoded.

Do I need to base64 encode the header? I assumed this is done for you? testing the same thing with curl works with no issues i.e.

curl -X POST -d "stuff=stuff" http://RqePZpAwyyVqal9D:[email protected]:8000/api/test/
like image 538
Prometheus Avatar asked Oct 31 '22 06:10

Prometheus


2 Answers

You do, in fact, need to base64 encode the auth strings yourself. In this case, I believe it should look something like:

import base64

auth = 'client_id %s client_secret %s' % (base64.b64encode(self.client_id),
                                          base64.b64encode(self.client_secret))
self.api.credentials(HTTP_AUTHORIZATION=auth)
like image 141
Joey Wilhelm Avatar answered Nov 11 '22 18:11

Joey Wilhelm


You never specify what type of authentication method you are using, so for now I'll assume you are using some form of OAuth (because of the client_id and client_secret).

When sending the OAuth credentials using the Authorization header, you must send them as Basic access authentication credentials. So that means they should be sent in the form of client_id:client_secret and base64 encoded before they are sent.

import base64

credentials = '%s:%s' % (self.client_id, self.client_secret)
authorization = 'Basic %s' % (base64.b64encode(credentials), )

self.api = APIClient()
self.api.credentials(HTTP_AUTHORIZATION=authorization)

response = self.api.post(url, payload)
like image 44
Kevin Brown-Silva Avatar answered Nov 11 '22 16:11

Kevin Brown-Silva