Flask OAuth 2.0 授权代码流使用 Fitbit API 的授权令牌无效

问题描述

我一直在尝试使用 Flask-dance 的 OAuth2ConsumerBlueprint 向 Fitbit API 发出请求。到目前为止,我已经设法让授权页面出现在我的 Flask 应用程序上,但我还没有能够路由到可以查看数据的页面

在浏览器中,当我尝试发出请求时,我得到了 CURL 响应的输出 {"errors":[{"errorType":"system","fieldName":"n/a","message":"Authorization Error: Invalid authorization token type"}],"success":false}

我现在的目标只是通过应用程序向“https://api.fitbit.com/1/user/-/p​​rofile .json"

这是我目前的代码。如果有人能就我在 Oauth2.0 授权代码流、flask 或 fitbit api 中出错的地方提供一些指导,我将不胜感激。

from flask import Flask,redirect,url_for,render_template
from flask_dance import OAuth2ConsumerBlueprint

import os
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'


CLIENT_ID = 'CLIENT_ID'  # OAuth 2.0 Client ID
CLIENT_SECRET = CLIENT_SECRET'
scope = ["activity","nutrition","heartrate","location","profile","settings","sleep","social","weight",]

# Flask OAuth2 Custom Blueprint for Fitbit API
app = Flask(__name__)
fitbit_blueprint = OAuth2ConsumerBlueprint(
    "fitbit-api",__name__,client_id=CLIENT_ID,client_secret=CLIENT_SECRET,base_url="https://www.fitbit.com",token_url="https://api.fitbit.com/oauth2/token",authorization_url="https://www.fitbit.com/oauth2/authorize",scope=scope
)
app.register_blueprint(fitbit_blueprint,url_prefix="/login")
app.secret_key = "supersecret"  # Replace this

app.token = fitbit_blueprint.token
print(app.token)


@app.route("/")
def index():
    #return redirect(url_for("fitbit-api.login"))
    return render_template('index.html')


@app.route("/success")
def access():
    return "Success"


@app.route('/login')
def login():
    return redirect(url_for("fitbit-api.login"))


# Redirect URI = http://127.0.0.1:
if __name__ == '__main__':
    app.run(host="localhost",port=5000,debug=True)

解决方法

在您获得 fitbit 授权之前,您无法访问(用户个人资料)资源。获得授权后,您需要将您的授权代码与令牌对交换,并将令牌(即 Access TokenRefresh Token)保存在代码中的某个位置。

仅能够到达并通过授权页面并不意味着您已获得授权。您可以在您的 fitbit 个人资料中检查您的授权是否已完成: 打开您的 Fitbit profile -> 我的仪表板 -> 设置。从左侧面板中选择应用程序。在那里您应该能够看到授权应用的列表:如果您没有看到,那么您还没有使用令牌对更改您的授权码!

只有这样您才能向用户配置文件端点发出请求,在这种情况下,您必须使用已保存的有效访问令牌在其标题如 https://dev.fitbit.com/build/reference/web-api/oauth2/#making-requests 中所示。