Created
September 22, 2015 21:29
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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