invalid_grant 通过 OAuth 2.0 获取访问令牌时出错

invalid_grant error while getting access token via OAuth 2.0

有一个 python 应用使用 Health Graph API

# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, redirect
from main.settings import CLIENT_ID, CLIENT_SECRET, RUNKEEPER_LOGIN_URL, ACCESS_TOKEN_URL
import requests


def index(request):
    return render_to_response('index.html')

def login(request):
    code = request.GET['code']
    post_data = {'grant_type': 'authorization_code',
                 'code': code,
                 'client_id': CLIENT_ID,
                 'client_secret': CLIENT_SECRET,
                 'redirect_uri': 'http://127.0.0.1:8000/welcome/'}

    req = requests.post(ACCESS_TOKEN_URL, data=post_data)

我的登录按钮将用户重定向到 Health Graph 登录页面,让我的应用等待授权代码。

<a href="https://runkeeper.com/apps/authorize?redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Flogin&response_type=code&client_id=xxxxxxxxx">

当我尝试通过调用登录函数获取访问令牌时,我收到 'invalid grant' 请求错误。我试图将 'authorization_code' 替换为另一个词,但我遇到了另一个 'unsupported grant type' 错误。换句话说,令牌服务器拒绝我从身份验证服务器获取的代码。我做错了什么?

重定向到授权端点中使用的 redirect_uri 与您在 login 函数中使用的不同,后者在令牌端点交换 code。正如 http://developer.runkeeper.com/healthgraph/getting-started 中的文档("Connect your Application to a User's Health Graph Account",项目符号 3.)规定的那样,它应该完全匹配:

redirect_uri: The exact URL that you supplied when sending the user to the authorization endpoint above