寻找简单的方法来为请求 API 的控制台程序设置回调 URL

问题描述 投票:0回答:1

我正在构建一个 python 程序,将 POST 请求发送到第 3 方 API。我是唯一的用户,不为其他人构建应用程序。我在我的Win11桌面上构建了程序,尝试从第3方查询(只读)数据。

问题在于 API 需要 3 足 OAuth。根据我的理解,我需要设置一个 Web 服务器并支付一个域名才能提供有效的回调 URL。是真的吗?

对于我的情况有更好的方法吗?我有 Azure 订阅。我可以为此目的设置一个静态网络应用程序吗?

python callback azure-web-app-service
1个回答
0
投票

首先,导航到“Azure Active Directory”>“应用程序注册”>“新注册”,创建应用程序注册后,将您的端点添加到其中,如下所示。

enter image description here

  • 选择支持的账户类型,并设置重定向URI(您可以使用
    http://localhost:5000/callback
    进行本地测试)。
  • 注册完成后,记下应用程序概述中的“应用程序(客户端)ID”和“目录(租户)ID”。

enter image description here

在 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
路由使用存储在会话中的访问令牌向第 3 方 API 发出示例 POST 请求 (
api_url
)

  • 运行 Flask 应用程序并在浏览器中访问
    http://localhost:5000/login
    以启动 OAuth 流程。 - 身份验证后,您将被重定向到回调 URL,并且访问令牌将存储在会话中。

enter image description here

访问

http://localhost:5000/make_api_request
使用获取的访问令牌发出 API 请求。

© www.soinside.com 2019 - 2024. All rights reserved.