gpt4 book ai didi

python - 如何使用 refresh_token 获取新的 access_token(使用 Flask-OAuthLib)?

转载 作者:太空狗 更新时间:2023-10-30 00:17:18 34 4
gpt4 key购买 nike

我正在使用 FLask Framework 构建网站 + 后端我在其中使用 Flask-OAuthlib与谷歌进行身份验证。身份验证后,后端需要定期扫描用户的 Gmail。因此,当前用户可以验证我的应用,我存储了 access_tokenrefresh_tokenaccess_token 一小时后过期,所以在这一小时内我可以像这样获取用户信息:

google = oauthManager.remote_app(
'google',
consumer_key='xxxxxxxxx.apps.googleusercontent.com',
consumer_secret='xxxxxxxxx',
request_token_params={
'scope': ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/gmail.readonly'],
'access_type': 'offline'
},
base_url='https://www.googleapis.com/oauth2/v1/',
request_token_url=None,
access_token_method='POST',
access_token_url='https://accounts.google.com/o/oauth2/token',
authorize_url='https://accounts.google.com/o/oauth2/auth'
)

token = (the_stored_access_token, '')
userinfoObj = google.get('userinfo', token=token).data
userinfoObj['id'] # Prints out my google id

一小时结束后,我需要使用 refresh_token(我已将其存储在我的数据库中)请求一个新的 access_token。我尝试将 the_stored_access_token 替换为 the_stored_refresh_token,但这只会给我一个Invalid Credentials 错误。

this github issue我阅读了以下内容:

regardless of how you obtained the access token / refresh token (whether through an authorization code grant or resource owner password credentials), you exchange them the same way, by passing the refresh token as refresh_token and grant_type set to 'refresh_token'.

由此我了解到我必须像这样创建一个远程应用程序:

google = oauthManager.remote_app(
'google',
# also the consumer_key, secret, request_token_params, etc..
grant_type='refresh_token',
refresh_token=u'1/xK_ZIeFn9quwvk4t5VRtE2oYe5yxkRDbP9BQ99NcJT0'
)

但这会导致 TypeError: __init__() got an unexpected keyword argument 'refresh_token'。所以从这里我有点迷路了。

有人知道如何使用 refresh_token 获取新的 access_token 吗?欢迎所有提示!

最佳答案

这就是我为 google 获取新的 access_token 的方式:

from urllib2 import Request, urlopen, URLError
from webapp2_extras import json
import mimetools
BOUNDARY = mimetools.choose_boundary()
def refresh_token()
url = google_config['access_token_url']
headers = [
("grant_type", "refresh_token"),
("client_id", <client_id>),
("client_secret", <client_secret>),
("refresh_token", <refresh_token>),
]

files = []
edata = EncodeMultiPart(headers, files, file_type='text/plain')
headers = {}
request = Request(url, headers=headers)
request.add_data(edata)

request.add_header('Content-Length', str(len(edata)))
request.add_header('Content-Type', 'multipart/form-data;boundary=%s' % BOUNDARY)
try:
response = urlopen(request).read()
response = json.decode(response)
except URLError, e:
...

EncodeMultipart 函数取自这里: https://developers.google.com/cloud-print/docs/pythonCode

一定要使用相同的边界

关于python - 如何使用 refresh_token 获取新的 access_token(使用 Flask-OAuthLib)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27146469/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com