Skip to content

Instantly share code, notes, and snippets.

@pgstenberg
Last active August 2, 2021 07:25
Show Gist options
  • Save pgstenberg/daf27122eb113baf8acf874cb9c86b43 to your computer and use it in GitHub Desktop.
Save pgstenberg/daf27122eb113baf8acf874cb9c86b43 to your computer and use it in GitHub Desktop.
Simple python3 snippet for handling a oauth2 code callback by redeeming it and proxy back the response from the oauth2 server.
#!/usr/bin/env python
import sys, http.client, ssl, urllib.parse
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def __init__(self, callback_url, token_url, client_id, client_secret):
self.callback_url = callback_url
self.token_url = token_url
self.client_id = client_id
self.client_secret = client_secret
def __call__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def do_GET(self):
query_paramaters = parse_qs(urlparse(self.path).query)
""" return if code query is not present. """
if 'code' not in query_paramaters:
return
""" Redeem code from oauth2 server """
code = str(query_paramaters['code'][0])
parsed_token_url = urlparse(self.token_url)
params = urllib.parse.urlencode({
'code': str(code),
'client_id': self.client_id,
'client_secret': self.client_secret,
'redirect_uri': self.callback_url,
'grant_type': 'authorization_code'
})
headers = {
'Content-type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
conn = http.client.HTTPSConnection(
parsed_token_url.netloc,
context = ssl._create_unverified_context()
) if parsed_token_url.scheme == 'https' else http.client.HTTPConnection(
parsed_token_url.netloc
)
conn.request(
"POST",
parsed_token_url.path,
params,
headers
)
response = conn.getresponse()
""" Respond to client with oauth2 token response """
self.send_response(200)
self.send_header(
"Content-type",
response.headers['content-type']
)
self.end_headers()
self.wfile.write(response.read())
callback_url = str(sys.argv[1])
handler = SimpleHTTPRequestHandler(
callback_url, # callback_url
str(sys.argv[2]), # target_url
str(sys.argv[3]), # client_id
str(sys.argv[4]) # client_secret
)
httpd = HTTPServer(
(
urlparse(callback_url).hostname,
urlparse(callback_url).port
),
handler
)
print("Hosting on " + callback_url)
httpd.serve_forever()
@pgstenberg
Copy link
Author

example:
python3 oauth2-code-callback-handler.py http://localhost:8000 https://localhost:8443/oauth/v2/oauth-token test-client client-secret

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment