英文:
How do I handle obtaining an OAuth authorization grant in my Python Script after a redirect?
问题
我需要编写一个Python脚本来运行OAuth 2.0客户端端流程。在这个流程中,我需要用户运行Python脚本,打开浏览器进行登录和授权,然后获取授权许可以交换为访问令牌并继续流程。我一直在搜索,但没有找到一个好的答案来解决这个问题,因为大多数示例都没有涉及到实际的OAuth登录,或者需要复制/粘贴。是否有一种干净的方式可以将流程无缝集成到我的Python代码中以供本地使用?
我曾尝试过使用线程和http创建一个本地主机服务器来获取请求,尝试过使用flask进行实验,并尝试查看创建协议处理程序是否有所帮助。我在所有这些方面都取得了一些成功,并且能够完成整个流程,但似乎仍然无法从重定向URI中获取授权码。该脚本将在内部运行,不会被分发,但至少需要足够干净,以免必须复制/粘贴。
英文:
I need to write a Python script to run an OAuth 2.0 client side flow. In the flow, I need to have the user run the Python script, have the browser open to log in and grant access, then obtain the Authorization Grant to trade in for the Access Token and continue the flow. I have been searching and haven't found a good answer on how to do this as most examples don't involve an actual OAuth login or require copy/paste. Is there a clean way to seamlessly integrate the flow into my Python code for local use?
I have briefly tried threading and http to create a localhost server to obtain the request, have experimented with flask, and have tried looking to see if creating a protocol handler could be of help. I had some success with all of these and am able to get through the flow, but still can't seem to pull the Authorization code from the redirect uri. The script will be run internally and won't be distributed, but needs to at least be clean enough that copy/pasting doesn't have to happen.
答案1
得分: 0
以下将创建一个临时的本地主机,并允许从URL中获取授权授予并检索并返回访问令牌。
import requests
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
import webbrowser
access_token = None
# 简单的HTTP请求处理程序以捕获授权代码
class AuthorizationHandler(BaseHTTPRequestHandler):
authorization_code = None
def do_GET(self):
global access_token
if self.path.startswith("/oauth-callback?"):
# 从查询参数中提取授权代码
authorization_code = self.path.split("&code=")[1]
# 显示授权代码
print("Authorization Code:", self.authorization_code)
# 向浏览器发送响应
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(b"<h1>Authorization Code Received</h1>")
# 获取OAuth客户端访问令牌
headers = {'accept': '*/*'}
parameters = {'client_id': '{{Client_ID}}', 'client_secret': '{{Client_Secret}}', 'access_code': authorization_code}
response = requests.get("{{tokenURL}}", headers=headers, params=parameters)
print(response.text)
token = response.text
# 使用OAuth的访问令牌登录
headers = {'accept': '*/*', 'Content-Type': 'application/json'}
body = {'token': token}
response = requests.post("{{loginURL}}", headers=headers, json=body)
print(response.text)
json_response = response.json()
access_token = json_response["token"]
# 获取令牌后退出函数
raise SystemExit
# 在单独的线程中启动临时HTTP服务器
def start_temp_server():
server = HTTPServer(("localhost", 8000), AuthorizationHandler)
server.serve_forever()
# 示例用法
authorization_url = "{{AuthorizationURL}}"
# 在单独的线程中启动临时服务器
server_thread = threading.Thread(target=start_temp_server)
server_thread.start()
# 在默认的Web浏览器中打开授权URL
webbrowser.open(authorization_url)
server_thread.join()
英文:
The following will create a temporary localhost and allow the scraping of the Authorization Grant from the URL along with retrieving and returning the Access Token.
import requests
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
import webbrowser
access_token = None
# Simple HTTP request handler to capture the authorization code
class AuthorizationHandler(BaseHTTPRequestHandler):
authorization_code = None
def do_GET(self):
global access_token
if self.path.startswith("/oauth-callback?"):
# Extract the authorization code from the query parameters
authorization_code = self.path.split("&code=")[1]
# Display the authorization code
print("Authorization Code:", self.authorization_code)
# Send a response to the browser
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(b"<h1>Authorization Code Received</h1>")
# Obtain OAuth Client Access Token
headers = {'accept':'*/*'}
parameters = {'client_id':'{{Client_ID}}','client_secret':'{{Client_Secret}}','access_code':authorization_code}
response = requests.get("{{tokenURL}}",headers=headers,params=parameters)
print(response.text)
token = response.text
# Log in using Access Token from OAuth
headers = {'accept':'*/*','Content-Type':'application/json'}
body = {'token':token}
response = requests.post("{{loginURL}}",headers=headers,json=body)
print(response.text)
json_response = response.json()
access_token= json_response["token"]
# Exit the function after obtaining the token
raise SystemExit
# Start a temporary HTTP server in a separate thread
def start_temp_server():
server = HTTPServer(("localhost", 8000), AuthorizationHandler)
server.serve_forever()
# Example usage
authorization_url = "{{AuthorizationURL}}"
# Start the temporary server in a separate thread
server_thread = threading.Thread(target=start_temp_server)
server_thread.start()
# Open the authorization URL in the default web browser
webbrowser.open(authorization_url)
server_thread.join()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论