Skip to content

Instantly share code, notes, and snippets.

@xrl
Created September 22, 2015 21:29
Show Gist options
  • Save xrl/7242136520f002a7201d to your computer and use it in GitHub Desktop.
Save xrl/7242136520f002a7201d to your computer and use it in GitHub Desktop.
The duo API documentation gives a snippet for generating headers but does not give a full example, here's one that works (and hopefully gets indexed by google)
import base64, email, hmac, hashlib, urllib
import httplib, logging
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
SKEY = 'FILL_ME_IN'
IKEY = 'FILL_ME_IN'
API_HOSTNAME = 'FILL_ME_IN'
def sign(method, host, path, params, skey, ikey):
"""
Return HTTP Basic Authentication ("Authorization" and "Date") headers.
method, host, path: strings from request
params: dict of request parameters
skey: secret key
ikey: integration key
"""
# create canonical string
now = email.Utils.formatdate()
canon = [now, method.upper(), host.lower(), path]
args = []
for key in sorted(params.keys()):
val = params[key]
if isinstance(val, unicode):
val = val.encode("utf-8")
args.append(
'%s=%s' % (urllib.quote(key, '~'), urllib.quote(val, '~')))
canon.append('&'.join(args))
canon = '\n'.join(canon)
# sign canonical string
sig = hmac.new(skey, canon, hashlib.sha1)
auth = '%s:%s' % (ikey, sig.hexdigest())
# return headers
return {'Date': now, 'Authorization': 'Basic %s' % base64.b64encode(auth)}
duoconn = httplib.HTTPSConnection(API_HOSTNAME)
duoconn.debuglevel = 1
duoconn.request('GET', '/admin/v1/logs/authentication', "", sign('GET', API_HOSTNAME, '/admin/v1/logs/authentication', {}, SKEY, IKEY))
print("got: %s", repr(duoconn.getresponse()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment