FlowExchangeError:flask应用程序中的invalid_grant

时间:2013-09-01 22:37:43

标签: python youtube-api google-oauth flask

我正在创建一个包装谷歌oauth的API。我正在使用谷歌python客户端库。

api.py中的代码

from flask import request, g
from ..helpers import config_helper
from ..adapters.youtube.oauth_adapter import OauthAdapter
from ..api import api_blueprint as api


@api.before_app_request
def before_request():
    client_id, client_secret, scope, callback = config_helper.get_config()
    g.auth = OauthAdapter(client_id, client_secret, scope, callback)


@api.route('/authorisation_url/')
def authorisation_url():
    auth = g.get('auth', None)
    return auth.get_authorisation_url()


@api.route('/oauth2callback/')
def callback():
    authorisation_code = request.args.get('code')
    return authorisation_code


@api.route('/save_oauth2credential/', methods=['POST'])
def oauth2_credentials():
   auth = g.get('auth', None)
   user = request.form.get('user')
   authorisation_code = request.form.get('authorisation_code')
   auth.save_credentials(user, authorisation_code)


@api.teardown_app_request
def after_request(response):
    g.auth = None
    return response

oauth_adapter.py中的代码

from oauth2client.client import OAuth2WebServerFlow
from ..repositories import oauth_credentials_repository


class OauthAdapter:
    def __init__(self, client_id, client_secret, scope, callback):
        self.flow = OAuth2WebServerFlow(client_id=client_id,
                                    client_secret=client_secret,
                                    scope=scope,
                                    redirect_uri=callback)

    def get_authorisation_url(self):
        return self.flow.step1_get_authorize_url()

    def save_credentials(self, user, authorisation_code):
        credentials = self.flow.step2_exchange(authorisation_code)
        oauth_credentials_repository.save(user, credentials, 'Google')

我需要针对登录用户保存凭据对象,以便我以后可以使用它代表此用户拨打其他google api。

当我调用@ api.route('/ save_oauth2credential /',methods = ['POST'])时,使用在@ api.route('/ oauth2callback /')步骤中检索到的authorisation_code来检索凭据。我一直收到FlowExchangeError:invalid_grant

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

查看Chrome Devtools中的网络对话,了解网络内容。我猜这里有一个403无效的授权响应。所以你需要弄清楚无效授权的原因。我刚刚在Getting 'invalid_grant' error with google oauth from second time

发布了一些可能的解释

一般来说,您需要做两件事。

首先,检查您的代码是否正确,您的范围和客户端ID是否正确,以及您是否正确保存了刷新令牌。

完成所有这些操作后,您需要将无效授权作为职业危害处理,并重新授权用户进行授权以获取新的刷新令牌。