Skip to content

Instantly share code, notes, and snippets.

@johngrimes
Created February 27, 2024 00:06
Show Gist options
  • Save johngrimes/1b4d66c9dd8c4f7cbaf94aadb84e503b to your computer and use it in GitHub Desktop.
Save johngrimes/1b4d66c9dd8c4f7cbaf94aadb84e503b to your computer and use it in GitHub Desktop.
OAuth2 client credentials test harness
import requests
def get_oauth2_token(client_id, client_secret, token_url):
"""
Obtain an OAuth2 token using client credentials grant.
:param client_id: OAuth2 Client ID
:param client_secret: OAuth2 Client Secret
:param token_url: OAuth2 Token Endpoint URL
:return: The token if successful, None otherwise.
"""
# Set up the data for the token request
data = {
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
'scope': '[your scope]'
}
# Prepare the request for logging
request = requests.Request('POST', token_url, data=data).prepare()
# Print raw request details
print("Raw Request Details:")
print(f"URL: {request.url}")
print("Headers:", request.headers)
print("Body:", request.body)
# Make a POST request to the token endpoint
with requests.Session() as session:
response = session.send(request)
# Check if the request was successful
if response.status_code == 200:
# Parse the token from the response
token = response.json().get('access_token')
return token
else:
# Print diagnostic information in case of an error
print(f"Failed to obtain token, status code: {response.status_code}")
print("Response reason:", response.reason)
try:
# Attempt to parse and print the error message from the response body
error_info = response.json()
print("Error details:", error_info)
except ValueError:
# If response is not in JSON format, print the raw response text
print("Error response:", response.text)
return None
# Example usage
if __name__ == "__main__":
CLIENT_ID = '[your client]'
CLIENT_SECRET = '[your secret]'
TOKEN_URL = '[your endpoint]'
token = get_oauth2_token(CLIENT_ID, CLIENT_SECRET, TOKEN_URL)
if token:
print("Token obtained successfully:", token)
else:
print("Failed to obtain token.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment