我正在创建一个 API 来包装 google oauth。我正在使用谷歌 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/') 步骤中检索到的授权码检索凭据时。我不断收到 FlowExchangeError: invalid_grant
有任何想法吗?