首页 > 解决方案 > 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.');
        }
    });
}

标签: javascriptfirebase-authenticationgoogle-signin

解决方案


您可以使用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.
  });

推荐阅读