我正在构建一个Python程序,发送POST请求到第三方API。我是唯一的用户,而不是为其他人构建应用程序。我在我的Win 11桌面上构建了该程序,尝试从第三方查询(只读)数据。问题是API需要3-Legged OAuth。根据我的理解,我需要设置一个Web服务器并支付域名,以便提供有效的回调URL。这是真的吗?对于我的情况,有更好的方法吗?我有Azure订阅。我可以为此设置静态Web应用程序吗?
3xiyfsfu1#
首先,导航到“Azure Active Directory”>“应用程序注册”>“新建注册”,创建应用程序注册后,然后将您的端点添加到其中,如下所示。x1c 0d1x的数据
http://localhost:5000/callback
的
在Flask应用程序中实施OAuth流
from flask import Flask, request, redirect, url_for, session, jsonify from msal import ConfidentialClientApplication import requests app = Flask(__name__) app.secret_key = "your_secret_key" # Azure AD application details client_id = "your_client_id" client_secret = "your_client_secret" authority = "https://login.microsoftonline.com/your_tenant_id" # 3rd party API details api_url = "https://api.example.com/endpoint" @app.route('/') def home(): return "Home Page" @app.route('/login') def login(): auth_url = ( f"{authority}/oauth2/v2.0/authorize?" f"client_id={client_id}" "&response_type=code" "&redirect_uri=http://localhost:5000/callback" "&scope=User.Read" # Adjust scopes based on your API permissions ) return redirect(auth_url) @app.route('/callback') def callback(): if "code" in request.args: code = request.args["code"] cca = ConfidentialClientApplication( client_id, client_secret, authority, post_logout_redirect_uri="http://localhost:5000" ) token_response = cca.acquire_token_by_authorization_code( code, scopes=["User.Read"], redirect_uri="http://localhost:5000/callback" ) session["access_token"] = token_response["access_token"] return "Authentication successful! You can now make API requests." return "Authentication failed." @app.route('/make_api_request') def make_api_request(): access_token = session.get("access_token") if access_token: # Make a sample API request using the obtained access token headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json' } try: # Replace this with the actual payload and endpoint of the 3rd party API api_data = {'key1': 'value1', 'key2': 'value2'} response = requests.post(api_url, headers=headers, json=api_data) if response.status_code == 200: return jsonify(response.json()) else: return f"Error: {response.status_code}\nResponse: {response.text}" except Exception as e: return f"An error occurred: {str(e)}" else: return "Access token not found. Please authenticate first." if __name__ == '__main__': app.run(port=5000)
字符串/make_api_request路由使用会话中存储的访问令牌向第三方API(api_url)发出示例POST请求
/make_api_request
api_url
http://localhost:5000/login
的访问http://localhost:5000/make_api_request,使用获得的访问令牌发出API请求。
http://localhost:5000/make_api_request
1条答案
按热度按时间3xiyfsfu1#
首先,导航到“Azure Active Directory”>“应用程序注册”>“新建注册”,创建应用程序注册后,然后将您的端点添加到其中,如下所示。
x1c 0d1x的数据
http://localhost:5000/callback
进行本地测试)。的
在Flask应用程序中实施OAuth流
字符串
/make_api_request
路由使用会话中存储的访问令牌向第三方API(api_url
)发出示例POST请求http://localhost:5000/login
以启动OAuth流。-身份验证后,您将被重定向到回调URL,访问令牌将存储在会话中。的
访问
http://localhost:5000/make_api_request
,使用获得的访问令牌发出API请求。