首页 > 解决方案 > 如何在 Firebase 中重新对用户进行身份验证?

问题描述

目前,我和我的团队正在尝试开发一种完全有效的重新认证机制。我们遇到了从 Firebase 获取新令牌的问题。首先,我们让人们用谷歌登录,代码如下:

loginUserWithGoogle(): Promise<any> {
    const provider = new firebase.auth.GoogleAuthProvider();
    provider.addScope('https://mail.google.com');
    return this._af.auth.signInWithPopup(provider);
}

用户登录后,我们有access_tokenrefresh_token。借助 Gmail API 和 GAPI 库,用户可以从 Gmail 中查看自己的电子邮件。

 gapi.load('client', () => {
        gapi.client.setToken({access_token: <SAVED ACCESS TOKEN>});
        gapi.client.init({
            apiKey: '<API KEY>',
            clientId: '<CLIENT ID>',
            discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest'],
            scope: 'https://mail.google.com/'
        });

        gapi.client.load('gmail', 'v1', () => {
            ...
        })
})

这非常有效,但access_token的过期时间设置为 1 小时。在那之后,我们会收到来自 Gmail API 的 403 错误代码。所以我们要做的是,我们发送一个 POST 请求(带有查询参数 grant_type= refresh_token &refresh_token= REFRESH_TOKEN)到...

https://securetoken.googleapis.com/v1/token?key=YOUR_API_KEY

...我们收到一个新令牌并用新令牌替换旧令牌。在比较了 2 个令牌(1 个最初从 Firebase 接收,1 个从 API 接收)后,我们得出结论,这 2 个令牌完全不同,替换后我们仍然收到 403 错误。

有没有办法使用 Firebase 重新对用户进行身份验证?

标签: angularfirebaseoauthfirebase-authenticationgmail-api

解决方案


完成:唯一有效的解决方案是将 Gapi JavaScript 客户端与 Firebase 集成,并创建一个每 30 分钟运行一次的间隔,并触发一个刷新访问令牌的函数:

gapi.auth2.getAuthInstance().currentUser.get().reloadAuthResponse().then((currUser: any) => {
      // do something with currUser.access_token (new access token)
});

推荐阅读