无法使用Python从Dropbox auth api获取access_token

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

我尝试了很多,这是我的 python 代码,用于使用手动生成的 access_token 并防止其过期(因为其生命周期仅为 4 小时),因此它将使用刷新令牌来重新获取新的访问令牌,但是,它不断向我显示此错误:

Error: 400 - {"error": "invalid_grant", "error_description": "code doesn't exist or has expired"}

我的完整代码是:

import base64
import requests

app_key = '<APP KEY>'
app_secret = '<APP SECRET HERE>'
redirect_uri = 'http://localhost/callback'
access_code = 'ACCESS CODE GOES HERE'

def get_access_token(app_key, app_secret, access_code, redirect_uri):
    # Create headers
    headers = {
        'Authorization': 'Basic ' + base64.b64encode(f"{app_key}:{app_secret}".encode()).decode(),
        'Content-Type': 'application/x-www-form-urlencoded'
    }

    # Create data for the POST request
    data = {
        'code': access_code,
        'grant_type': 'authorization_code',
        'redirect_uri': redirect_uri
    }

    # Make the POST request to get an access token
    response = requests.post('https://api.dropboxapi.com/oauth2/token', headers=headers, data=data)
    print(response.status_code)

    if response.status_code == 200:
        response_data = response.json()
        access_token = response_data.get('access_token')
        refresh_token = response_data.get('refresh_token')
        if access_token:
            print("Access Token:", access_token)
            if refresh_token:
                print("Refresh Token:", refresh_token)
        else:
            print("No access token found in response.")
    else:
        print(f"Error: {response.status_code} - {response.text}")

get_access_token(app_key, app_secret, access_code, redirect_uri)

我多次尝试手动生成新的访问令牌并使用它,但响应永远不会改变

python authentication oauth-2.0 dropbox refresh-token
1个回答
0
投票

您似乎正在尝试在您的

access_code
变量中重复使用“授权代码”,有时也称为“访问代码”。

但是 Dropbox 授权码不能重复使用。每个 Dropbox 授权码的有效期只有几分钟,并且只能使用一次。应用程序应该在收到授权代码后立即交换一次授权代码,以接收访问令牌和可选的刷新令牌。仅当请求“离线”访问时才会返回刷新令牌。

刷新令牌不会自动过期,可以重复使用。您可以在 Dropbox OAuth 指南授权文档 中找到更多信息。 这篇博文中有处理此流程的基本轮廓,这可以作为一个有用的示例。

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