javascript - Firebase 身份验证和 Google 登录
问题描述
我正在使用javascript登录firebase auth,我希望使用相同的过程访问google驱动器以避免两次登录google。
查看https://firebase.google.com/docs/auth/web/google-signin上的文档,我可以看到它说“这给了你一个谷歌访问令牌。你可以用它来访问谷歌 API。”
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// ...
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
目前,我可以通过之后调用它来分别登录它们:
gapi.auth2.getAuthInstance().signIn();
但这会为用户产生两次登录。目前的目标是让用户登录 firebase auth,然后在没有双重登录的情况下从 google 列出用户的文件。
function appendPre(message) {
var pre = document.getElementById('form-results-ul');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
function listFiles() {
gapi.client.drive.files.list({
'pageSize': 10,
'fields': "nextPageToken, files(id, name)"
}).then(function (response) {
appendPre('Files:');
var files = response.result.files;
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
appendPre(file.name + ' (' + file.id + ')');
}
} else {
appendPre('No files found.');
}
});
}
解决方案
您可以使用gapi.auth2.getAuthInstance().signIn()
登录,然后使用该库中的 Google ID 令牌登录 Firebase 身份验证。
这记录在Firebase 官方文档中。
// Build Firebase credential with the Google ID token.
const credential = firebase.auth.GoogleAuthProvider.credential(
googleUser.getAuthResponse().id_token);
// Sign in with credential from the Google user silently.
firebase.auth().signInWithCredential(credential)
.then((result) => {
// User signed in.
})
.catch((error) => {
// Error occurred.
});
推荐阅读
- go - 如何同时从速率受限的 API 端点获取?
- python - Tkinter组合框回调无限循环?
- typescript - @stripe/react-stripe-js - 如何使用 Typescript 在 createPaymentMethod 上正确输入 paymentType
- python - 如何更改系列的索引?系列没有 set_index 方法
- r - 根据 R dplyr / tidyverse 数据框的多列获取最大日期
- string - 在 Postgresql 中的字符串中排序逗号分隔值
- dataframe - 使用 XLSX.gettable 读取非连续列?
- c++ - SFINAE - 如果参数是可复制构造的,则启用一个函数,否则启用另一个函数
- java - 遍历map的时候顺序是怎么决定的
- c# - 在 C# 中获得奇怪的价值