我在python应用程序中使用gspread来访问一些后端Google表格,这些表格用作该应用程序的数据库。要求用户使用应用内浏览器登录到应用,然后使用url中通过此方法返回的令牌创建authlib OAuth2会话。最初的登录和访问工作正常,但是当令牌在一个小时后超时时,我将访问工作表,并且应用程序中断。
我不知道如何使用authlib刷新令牌,我们选择该库的原因是因为它与gspread集成在一起,并且应该为您自动刷新auth令牌。我用于登录的代码如下,但是一个小时后,由于身份验证问题,gspread函数open_by_key()
失败了。
我尝试过重新创建gspread客户端,但这只使用了相同的令牌。我觉得应该有一种刷新令牌的方法,将令牌的寿命再延长一个小时,但我找不到如何使用authlib来做到这一点。
creds = OAuth2Session(clientId, clientSecret, scope=scope, redirect_uri=redirectUrl)
authUrl, state = creds.create_authorization_url('https://accounts.google.com/o/oauth2/v2/auth', response_type='token')
在浏览器中加载authURL
并使用户登录。浏览器将身份验证响应作为urlString
creds.fetch_access_token(authorization_response=urlString)
gc = gspread.Client(None, creds)
ss = gc.open_by_key(sheetKey)
todaysSheetName = datetime.datetime.now().strftime('%d-%m-%Y')
wks = ss.worksheet(todaysSheetName)
答案 0 :(得分:0)
authUrl, state = creds.create_authorization_url('https://accounts.google.com/o/oauth2/v2/auth', response_type='token')
根据您正在使用的这段代码,response_type=token
是隐式的授予类型流。我猜不会有带有隐式流程的令牌中的refresh_token
。这是我的建议:
refresh_token
交换新令牌。 refresh_token
方法很简单:
refresh_token(url=None, refresh_token=None, body='', auth=None, headers=None, **kwargs)
使用您的代码,应该是:
refresh_token = your_previous_token.refresh_token
new_token = creds.refresh_token('https://accounts.google.com/...', refresh_token=refresh_token)
问题在于此部分上没有文档。但是根据API,它会像这样使用。如果它不起作用,则可以将其报告给Authlib问题跟踪器。