Custom Authentication

Requests allows you to use specify your own authentication mechanism.

Any callable which is passed as the auth argument to a request method will have the opportunity to modify the request before it is dispatched.

Authentication implementations are subclasses of requests.auth.AuthBase, and are easy to define. Requests provides two common authentication scheme implementations in requests.auth: HTTPBasicAuth and HTTPDigestAuth.

Let’s pretend that we have a web service that will only respond if the X-Pizza header is set to a password value. Unlikely, but just go with it.

  1. from requests.auth import AuthBase
  2. class PizzaAuth(AuthBase):
  3. """Attaches HTTP Pizza Authentication to the given Request object."""
  4. def __init__(self, username):
  5. # setup any auth-related data here
  6. self.username = username
  7. def __call__(self, r):
  8. # modify and return the request
  9. r.headers['X-Pizza'] = self.username
  10. return r

Then, we can make a request using our Pizza Auth:

  1. >>> requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))
  2. <Response [200]>