Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Header-based auth class #6770

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions docs/user/authentication.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,27 @@ for using it::
Providing the credentials in a tuple like this is exactly the same as the
``HTTPBasicAuth`` example above.

Header Authentication
--------------------

Some services require authentication data in the header of the request.
Multiple headers can be added to an authentication object to keep them separate
from request data::

>>> from requests.auth import HTTPHeaderAuth
>>> auth = HTTPHeaderAuth({'Api-Key': '1234567890ABCDEF'}})
>>> response = requests.get('https://httpbin.org/headers', auth=auth)
>>> response.json()['headers']['Api-Key']
'1234567890abcdef'

Be aware that keys in the authentication object will override headers set by
the current request or session parameters::

>>> from requests.auth import HTTPHeaderAuth
>>> auth = HTTPHeaderAuth({'Api-Key': '1234567890ABCDEF'}})
>>> response = requests.get('https://httpbin.org/headers', headers={'Api-Key': '0000000000'}, auth=auth)
>>> response.json()['headers']['Api-Key']
'1234567890ABCDEF'

netrc Authentication
~~~~~~~~~~~~~~~~~~~~
Expand Down
11 changes: 11 additions & 0 deletions src/requests/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,17 @@ def __call__(self, r):
return r


class HTTPHeaderAuth(AuthBase):
"""Attaches authentication headers to the given Request object."""

def __init__(self, headers):
self.headers = headers

def __call__(self, r):
r.headers.update(self.headers)
return r


class HTTPDigestAuth(AuthBase):
"""Attaches HTTP Digest Authentication to the given Request object."""

Expand Down
39 changes: 38 additions & 1 deletion tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import requests
from requests.adapters import HTTPAdapter
from requests.auth import HTTPDigestAuth, _basic_auth_str
from requests.auth import HTTPDigestAuth, HTTPHeaderAuth, _basic_auth_str
from requests.compat import (
JSONDecodeError,
Morsel,
Expand Down Expand Up @@ -703,6 +703,43 @@ def get_netrc_auth_mock(url):
finally:
requests.sessions.get_netrc_auth = old_auth

def test_header_auth(self, httpbin):
header_key = "Test-Header"
header_value = "1234567890ABCDEF"
auth = HTTPHeaderAuth({header_key: header_value})
url = httpbin("headers")

# Check header exists
r = requests.get(url, auth=auth)
assert r.json()["headers"][header_key] == header_value

# Make sure it's not a fluke
r = requests.get(url)
assert header_key not in r.json()["headers"]

# Verify auth header overrides provided headers
# (not strictly a feature, but it's current behavior)
second_header_value = "NOT_RETURNED"
r = requests.get(url, headers={header_key: second_header_value}, auth=auth)
assert r.json()["headers"][header_key] == header_value

# Test with session
s = requests.session()
s.auth = auth
r = s.get(url)
assert r.json()["headers"][header_key] == header_value

# verify session header override
r = s.get(url, headers={header_key: second_header_value})
assert r.json()["headers"][header_key] == header_value

# Check sure multiple headers works
header_keys = ("Header-One", "Header-Two")
auth = HTTPHeaderAuth({key: key for key in header_keys})
r = requests.get(url, auth=auth)
returned_keys = r.json()["headers"].keys()
assert all(key in returned_keys for key in header_keys)

def test_DIGEST_HTTP_200_OK_GET(self, httpbin):
for authtype in self.digest_auth_algo:
auth = HTTPDigestAuth("user", "pass")
Expand Down