OAuth Bearer Token Using Python
As you build your own APIs, examining your use cases will help you decide which security methods to implement for them. For some use cases, API keys are sufficient; in others, you’ll want the additional protection and flexibility of tokens.
Solution
A bearer Token would include an embedded digital signature and be encrypted. The digital signature confirms that the token came from a trusted source. The use of encryption means only systems meant to be able to read the token can read it.
Recipe
- We are going to use the API from https://developer.here.com/, so please follow these steps to get your OAuth token. You will get a ‘credentials.properties’ file created from above, it contains two values of interest, the Access Key ID and the Access Key Secret. We will be needing them going forward. It looks like this:
here.user.id = HERE-USER_ID here.client.id = YOUR_CLIENT_ID here.access.key.id = YOUR_ACCESS_KEY here.access.key.secret = YOUR_ACCESS_KEY_SECRET here.token.endpoint.url = https://account.api.here.com/oauth2/token
cd your_folder virtualenv venv -p python3
import requests #Needed for making HTTP requests import time #Needed to generate the OAuth timestamp import urllib.parse #Needed to URLencode the parameter string from base64 import b64encode #Needed for create_signature function import hmac #Needed for create_signature function import hashlib #Needed for create_signature functionx import binascii#Needed for create_signature function
- grant_type — Value always remains same, «client_credentials»
- oauth_consumer_key — The Access Key ID value we acquired from credentials.properties file
- oauth_nonce — A unique string which never repeats
- oauth_signature_method — Always use «HMAC-SHA256»
- oauth_timestamp — The number of seconds since the Unix epoch, in simple words, the current time
- oauth_version — Always use «1.0»
The values of the parameter looks like this.
grant_type = 'client_credentials' oauth_consumer_key = 'HERE.ACCESS.KEY.ID' # replace your credentials.properties file access_key_secret = 'HERE.ACCESS.KEY.SECRET' # replace credentials.properties file oauth_nonce = str(int(time.time()*1000)) oauth_timestamp = str(int(time.time())) oauth_signature_method = 'HMAC-SHA256' oauth_version = '1.0'
The important thing here is that the type of all 6 parameters has to be string. For calculating nonce and timestamp we have used the time module of Python.
Next, we alphabetically combine all the parameters as a single string, separating each key value pair with an ampersand character («&») and then URL-encoding it.
def create_parameter_string(grant_type, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_version): parameter_string = '' parameter_string = parameter_string + 'grant_type=' + grant_type parameter_string = parameter_string + '&oauth_consumer_key=' + oauth_consumer_key parameter_string = parameter_string + '&oauth_nonce=' + oauth_nonce parameter_string = parameter_string + \ '&oauth_signature_method=' + oauth_signature_method parameter_string = parameter_string + '&oauth_timestamp=' + oauth_timestamp parameter_string = parameter_string + '&oauth_version=' + oauth_version return parameter_string parameter_string = create_parameter_string(grant_type, oauth_consumer_key,oauth_nonce,oauth_signature_method,oauth_timestamp,oauth_version) encoded_parameter_string = urllib.parse.quote(parameter_string, safe='')
The parameter_string is a simple concatenated output containing key-value pair separated by an ampersand character. With the help of the urllib python library, we got our URL-encoded output in encoded_parameter_string. It looks like this:
grant_type=client_credentials&oauth_consumer_key=XXXXXXXXXX&oauth_nonce=1585745318447&oauth_signature_method=HMAC-SHA256&oauth_timestamp=1585745318&oauth_version=1.0
grant_type%3Dclient_credentials%26oauth_consumer_key%3DXXXXXXXXXX%26oauth_nonce%3D1585745318447%26oauth_signature_method%3DHMAC-SHA256%26oauth_timestamp%3D1585745318%26oauth_version%3D1.0
url = 'https://account.api.here.com/oauth2/token' encoded_base_string = 'POST' + '&' + urllib.parse.quote(url, safe='') encoded_base_string = encoded_base_string + '&' + encoded_parameter_string
POST&https%3A%2F%2Faccount.api.here.com%2Foauth2%2Ftoken&grant_type%3Dclient_credentials%26oauth_consumer_key%3DXXXXXXXXXX%26oauth_nonce%3D1585747084344%26oauth_signature_method%3DHMAC-SHA256%26oauth_timestamp%3D1585747084%26oauth_version%3D1.0
access_key_secret = 'HERE.ACCESS.KEY.SECRET'#From credentials.properties file signing_key = access_key_secret + '&'
Combine all to create OAuth Signature The signature base string and the signing key created above, are passed to the HMAC-SHA256 Hashing Algorithm and the output is converted to a base64 string. Finally, we have our OAuth Signature.
def create_signature(secret_key, signature_base_string): encoded_string = signature_base_string.encode() encoded_key = secret_key.encode() temp = hmac.new(encoded_key, encoded_string, hashlib.sha256).hexdigest() byte_array = b64encode(binascii.unhexlify(temp)) return byte_array.decode() oauth_signature = create_signature(signing_key, encoded_base_string) encoded_oauth_signature = urllib.parse.quote(oauth_signature, safe='')
- oauth_consumer_key — The value of «here.access.key.id» from credentials.properties file
- oauth_nonce — Already have
- oauth_signature — The value of encoded_oauth_signature from above
- oauth_signature_method — «HMAC-SHA256»
- oauth_timestamp — Already have
- oauth_version — «1.0»
and append them to a string beginning with “OAuth”.
body = 'grant_type' : '<>'.format(grant_type)> headers = 'Content-Type' : 'application/x-www-form-urlencoded', 'Authorization' : 'OAuth oauth_consumer_key="",oauth_nonce="",oauth_signature="",oauth_signature_method="HMAC-SHA256",oauth_timestamp="",oauth_version="1.0"'.format(oauth_consumer_key,oauth_nonce,encoded_oauth_signature,oauth_timestamp) > response = requests.post(url, data=body, headers=headers) print(response.text)
The request body must contain grant_type value as ‘client_credentials’, always.
The output of the code looks like this-
"access_token":"eyJhbGci. ", "token_type":"bearer", "expires_in":86399 >
(venv) pip freeze > requirements.txt
import requests #Needed for making HTTP requests import time #Needed to generate the OAuth timestamp import urllib.parse #Needed to URLencode the parameter string from base64 import b64encode #Needed for create_signature function import hmac #Needed for create_signature function import hashlib #Needed for create_signature functionx import binascii#Needed for create_signature function grant_type = 'client_credentials' oauth_consumer_key = 'HERE.ACCESS.KEY.ID' #From credentials.properties file access_key_secret = 'HERE.ACCESS.KEY.SECRET'#From credentials.properties file oauth_nonce = str(int(time.time()*1000)) oauth_timestamp = str(int(time.time())) oauth_signature_method = 'HMAC-SHA256' oauth_version = '1.0' url = 'https://account.api.here.com/oauth2/token' # HMAC-SHA256 hashing algorithm to generate the OAuth signature def create_signature(secret_key, signature_base_string): encoded_string = signature_base_string.encode() encoded_key = secret_key.encode() temp = hmac.new(encoded_key, encoded_string, hashlib.sha256).hexdigest() byte_array = b64encode(binascii.unhexlify(temp)) return byte_array.decode() # concatenate the six Oauth parameters, plus the request parameters from above, sorted alphabetically by the key and separated by "&" def create_parameter_string(grant_type, oauth_consumer_key,oauth_nonce,oauth_signature_method,oauth_timestamp,oauth_version): parameter_string = '' parameter_string = parameter_string + 'grant_type=' + grant_type parameter_string = parameter_string + '&oauth_consumer_key=' + oauth_consumer_key parameter_string = parameter_string + '&oauth_nonce=' + oauth_nonce parameter_string = parameter_string + '&oauth_signature_method=' + oauth_signature_method parameter_string = parameter_string + '&oauth_timestamp=' + oauth_timestamp parameter_string = parameter_string + '&oauth_version=' + oauth_version return parameter_string parameter_string = create_parameter_string(grant_type, oauth_consumer_key,oauth_nonce,oauth_signature_method,oauth_timestamp,oauth_version) encoded_parameter_string = urllib.parse.quote(parameter_string, safe='') encoded_base_string = 'POST' + '&' + urllib.parse.quote(url, safe='') encoded_base_string = encoded_base_string + '&' + encoded_parameter_string # create the signing key signing_key = access_key_secret + '&' oauth_signature = create_signature(signing_key, encoded_base_string) encoded_oauth_signature = urllib.parse.quote(oauth_signature, safe='') #---------------------Requesting Token--------------------- body = 'grant_type' : '<>'.format(grant_type)> headers = 'Content-Type' : 'application/x-www-form-urlencoded', 'Authorization' : 'OAuth oauth_consumer_key="",oauth_nonce="",oauth_signature="",oauth_signature_method="HMAC-SHA256",oauth_timestamp="",oauth_version="1.0"'.format(oauth_consumer_key,oauth_nonce,encoded_oauth_signature,oauth_timestamp) > response = requests.post(url, data=body, headers=headers) print(response.text)
Feel free to see this git project as reference.
Python Post Request with Bearer Token Example
This article is focused on python post request with bearer token. This article goes in detailed on python post request with access token. This article goes in detailed on python header bearer token. you will learn python get request header bearer token.
Here, we will use requests library to all POST HTTP Request with header bearer token and get JSON response in python program. I will give you a very simple example to call POST Request with body parameters in python.
You can use these examples with python3 (Python 3) version.
let’s see below simple example with output:
import requests url = 'https://reqres.in/api/users' params = dict( name="Hardik", job="Developer", ) authToken = "abcd123. " headers = < 'Authorization': 'Bearer ' + authToken, 'Content-Type': 'application/json' >response = requests.post(url, params, headers) data = response.json() print(data)
Hardik Savani
I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Python Get First Date of Last Month Example
- Python Create Zip Archive from Directory Example
- How to Check if Today is Friday or not in Python?
- Python Check if Date is Weekend or Weekday Example
- Python PATCH Request with Parameters Example
- Python DELETE Request Example Tutorial
- Python PUT Request with Parameters Example
- Python POST Request with Parameters Example
- Python GET Request with Parameters Example
- How to Get Current Second in Python?
- How to Get Current Hour in Python?