Firebase认证和Google登录

3
我正在使用JavaScript登录Firebase身份验证,希望使用相同的过程访问Google Drive以避免两次登录Google。查看https://firebase.google.com/docs/auth/web/google-signin文档,我发现它说:“这会给您一个Google访问令牌。您可以使用它来访问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 Drive 上的文件。
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.');
        }
    });
}
1个回答

1
你可以使用 gapi.auth2.getAuthInstance().signIn() 进行登录,然后使用该库中的 Google ID 令牌进行 Firebase Auth 的登录。这在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.
  });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接