File: requests_auth.py

package info (click to toggle)
python-httpsig 1.3.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 224 kB
  • sloc: python: 601; makefile: 8
file content (40 lines) | stat: -rw-r--r-- 1,527 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import requests.auth
try:
    # Python 3
    from urllib.parse import urlparse
except ImportError:
    # Python 2
    from urlparse import urlparse

from .sign import HeaderSigner


class HTTPSignatureAuth(requests.auth.AuthBase):
    """
    Sign a request using the http-signature scheme.
    https://github.com/joyent/node-http-signature/blob/master/http_signing.md

    `key_id` is the mandatory label indicating to the server which secret to
      use secret is the filename of a pem file in the case of rsa, a password
      string in the case of an hmac algorithm
    `algorithm` is one of the six specified algorithms
      headers is a list of http headers to be included in the signing string,
      defaulting to "Date" alone.
    """
    def __init__(self, key_id='', secret='', algorithm=None, headers=None):
        headers = headers or []
        self.header_signer = HeaderSigner(
                                key_id=key_id, secret=secret,
                                algorithm=algorithm, headers=headers)
        self.uses_host = 'host' in [h.lower() for h in headers]

    def __call__(self, r):
        headers = self.header_signer.sign(
                r.headers,
                # 'Host' header unavailable in request object at this point
                # if 'host' header is needed, extract it from the url
                host=urlparse(r.url).netloc if self.uses_host else None,
                method=r.method,
                path=r.path_url)
        r.headers.update(headers)
        return r