Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Auth and Google Sign-in

I am using javascript to log into firebase auth and my hopes are to access google drive using the same process to avoid signing into google twice.

Looking at the docs at https://firebase.google.com/docs/auth/web/google-signin I can see that it says "This gives you a Google Access Token. You can use it to access the 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;
  // ...
});

Currently, I am able to log into them both separately by calling this afterward:

gapi.auth2.getAuthInstance().signIn();

but this produces two sign-ins for the user. The goal, for now, is to have the user sign into firebase auth and then list the user's files from google afterward without a double sign in.

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.');
        }
    });
}
like image 645
Zero Avatar asked Nov 21 '25 11:11

Zero


1 Answers

You can just use gapi.auth2.getAuthInstance().signIn() to sign in and then use the Google ID token from that library to sign in to Firebase Auth.

This is documented in 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.
  });
like image 175
bojeil Avatar answered Nov 23 '25 01:11

bojeil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!