【问题标题】:How to refresh firebase DB Auth token before it expires?如何在 Firebase DB Auth 令牌过期之前刷新它?
【发布时间】:2018-03-04 16:06:00
【问题描述】:
我正在使用 python 写入我的 firebase 数据库。我有数千个数据集,需要数小时才能完成。我的程序多次因此错误而停止
“身份验证令牌已过期”
我搜索了解决方案,但没有找到,后来我发现可以检查到期前的剩余时间并刷新令牌,这样数据传输就不会中断。
如何在令牌过期之前刷新它?
【问题讨论】:
标签:
python
firebase-realtime-database
firebase-authentication
access-token
【解决方案1】:
我正在使用带有 firebase 和 pyrebase 模块的 django。我也遇到了类似的问题。我在 github 上找到了解决方案:-> https://github.com/thisbejim/Pyrebase/issues/244
就在这段代码之后->
config = {
'apiKey': "your-api-key",
'authDomain': "your-auth-domain",
'databaseURL': "your-db-url",
'projectId': "your-project-id",
'storageBucket': "your-storage-bucket",
'messagingSenderId': "your-messaging-sender-id",
}
firebase = pyrebase.initialize_app(config)
auth = firebase.auth()
user = auth.sign_in_with_email_and_password("email@sthn.com", "strong-password")
添加这个
# A user's idToken expires after 1 hour, so be sure to use the user's refreshToken to avoid stale tokens.
user = auth.refresh(user['refreshToken'])
# now we have a fresh token
user['idToken']
【解决方案2】:
您可以在令牌即将到期时使用 google oauth2 lib 刷新令牌,如下所示:
import httplib2
from oauth2client.service_account import ServiceAccountCredentials
credentials = ServiceAccountCredentials.from_json_keyfile_name("service-account.json", "{scope}")
print(credentials.get_access_token())
credentials.refresh(httplib2.Http())
print(credentials.get_access_token())