New Forms of Authentication

If you can’t find a good implementation of the form of authentication you want, you can implement it yourself. Requests makes it easy to add your own forms of authentication.

To do so, subclass AuthBase and implement the __call__() method:

  1. >>> import requests
  2. >>> class MyAuth(requests.auth.AuthBase):
  3. ... def __call__(self, r):
  4. ... # Implement my authentication
  5. ... return r
  6. ...
  7. >>> url = 'http://httpbin.org/get'
  8. >>> requests.get(url, auth=MyAuth())
  9. <Response [200]>

When an authentication handler is attached to a request, it is called during request setup. The __call__ method must therefore do whatever is required to make the authentication work. Some forms of authentication will additionally add hooks to provide further functionality.

Further examples can be found under the Requests organization and in the auth.py file.