Last active
December 15, 2018 17:18
-
-
Save algorythm/41b3dcd727c781bcf4e587b94b65f50f to your computer and use it in GitHub Desktop.
OAuth Client
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
| from http.server import BaseHTTPRequestHandler, HTTPServer | |
| import webbrowser | |
| def get_code_from_httpserver(address = "127.0.0.1", port = 8000): | |
| """ | |
| Starts a webserver | |
| When a GET request with query parameter "?code=something" is | |
| received, stop the webserver and return that code | |
| """ | |
| print(f"Serving at port {port}. Waiting for authentication...") | |
| class AuthServerHandler(BaseHTTPRequestHandler): | |
| def do_GET(self): | |
| self.send_header("Content-type", "text/html") | |
| self.end_headers() | |
| query=self.path[1:].split("%7C")[0] | |
| # if query ?code is used | |
| if query.startswith("?code="): | |
| # i.e. GET http://127.0.0.1:8000?code=AuthenticationCode | |
| code = query.replace("?code=", "") | |
| print(f"Code: {code}") | |
| # Here I want to stop the webserver, and return the code | |
| httpd = HTTPServer((address, port), AuthServerHandler) | |
| httpd.serve_forever() | |
| def get_github_link(client_id, redirect_uri): | |
| return f"https://github.com/login/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}/" | |
| def open_auth(): | |
| webbrowser.open(get_github_link("MyClientId", "127.0.0.1:8000"), new=0, autoraise=True) | |
| open_auth() | |
| code = get_code_from_httpserver() | |
| # Now contact some other service that will use that code | |
| # to get a token from the oauth server |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment