Testing, Django Client, and HTTP Basic Access Authentication

I was writing a test using the django client against some code that uses http basic authentication. I had to dig for hours to figure this out, so I figured I’d post my solution somewhere.

def create_auth_string(username, password):
  import base64
  credentials = base64.encodestring("%s:%s" % (username, password)).rstrip()
  auth_string = 'Basic %s' % credentials
  return auth_string

# create auth string for header
auth_string = create_auth_string("user", "pass")

# This is where the magic happens
response = self.client.get('/url/requiring/authorization/', HTTP_AUTHORIZATION=auth_string)

Not complicated, but not documented anywhere I could find. Enjoy!

This entry was posted in Development. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>