javascript - Firebase 身份验证和 Google 登录

标签 javascript firebase-authentication google-signin

我正在使用 javascript 登录 firebase auth,我希望使用相同的过程访问 google drive 以避免登录 google 两次。

查看 https://firebase.google.com/docs/auth/web/google-signin 上的文档我可以看到它说“这为您提供了一个 Google 访问 token 。您可以使用它来访问 Google 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 token 登录 Firebase Auth。

这记录在 Firebase Official docs 中.

// 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.
  });

关于javascript - Firebase 身份验证和 Google 登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58068382/

相关文章:

javascript - aasy 函数结束后返回函数的值

firebase - 如何返回 firebase 用户以访问某些元素

ios - 如何检测电子邮件地址更改是否已还原?

cocoapods - GoogleMobileVision GoogleSignIn 使用 Cocoapods 重复符号?

android - Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) 返回 null

ios - Google 登录在允许后重定向到 google.com 而不是应用程序

javascript - Chrome 扩展 : Refresh popup. html 到新的 html 页面

javascript - 如何在 NodeJS 中导入匿名闭包

javascript - HAML 中的 JS 中的 Ruby : what's the syntax?

flutter - 如何在 Flutter 中将 firebase 匿名用户迁移到经过身份验证的用户