OAuth1 implementation using requests library in Python

109 Views Asked by At

I'm trying implement OAuth1 using requests library in Python.

import random
import time
import string
import hmac
import base64
import hashlib
import requests
from urllib.parse import quote
​
consumer_key = ""
consumer_secret = ""
access_token = ""
access_token_secret = ""
url = "https://mdmenrollment.apple.com/session"
​
timestamp = str(int(time.time()))
nonce_length = 16
nonce = ''.join(random.choices(string.digits, k=nonce_length))
nonce = nonce + timestamp
​
nonce, timestamp, consumer_key, consumer_secret, access_token, access_token_secret = map(quote, (nonce, timestamp, consumer_key, consumer_secret, access_token, access_token_secret))
base_string = f"{consumer_key}&{nonce}&{timestamp}&{access_token}"
key = f"{consumer_secret}&{access_token_secret}"
signature = quote(base64.b64encode(hmac.new(key.encode('utf-8'), base_string.encode('utf-8'), hashlib.sha1).digest()).decode('utf-8'))
​
auth_header = f'OAuth oauth_nonce="{nonce}", oauth_timestamp="{timestamp}", oauth_version="1.0", oauth_signature_method="HMAC-SHA1", oauth_consumer_key="{consumer_key}", oauth_token="{access_token}", oauth_signature="{signature}"'
print(auth_header)
​
request = requests.get(url, headers={'Authorization': auth_header})
print(request.text)

The request works if I use oauth2 or requests-oauthlib. The problem seems to be with signature or nonce but the response that I get back is just bad request so I'm not sure what am I doing wrong. Can someone tell me a better way to implement this using requests module.

0

There are 0 best solutions below