An example of how to use GAPI and Firebase Auth together to authenticate users and talk to Google APIs.
Have a question? Book a slot to chat further or open an issue
This is a hard fork of the repo msukmanowsky/gapi-firebase. You may wish to contact the author for direct advice. Visit the page.
If you are trying to use Google's JavaScript Library to query Google APIs (e.g. Google Apps Script Executable API), you'll run into an issue whereby Firebase Auth is strictly intended for AuthN (fetching a user's identity and not AuthZ (authorizing a user to access specific resources).
The access token that Firebase Auth provides is valid for whatever scopes a user approved, but Firebase Auth does not provide any means to see the access token upon, say, token refreshes. This is by design.
Google's JavaScript Library transparently handles token refreshes but will also provide access to the updated token via:
const auth2 = gapi.auth2.getAuthInstance();
auth2.isSignedIn.listen((isSignedIn) => {
if (isSignedIn) {
const currentUser = auth2.currentUser.get();
const authResponse = currentUser.getAuthResponse(true);
authResponse.id_token;
authResponse.access_token;
}
});These same credentials can also be used to authorize a user to Firebase!
const credential = firebase.auth.GoogleAuthProvider.credential(
authResponse.id_token,
authResponse.access_token
);
firebase.auth().signInWithCredential(credential);There are some additional concerns to keep in mind like signing out of both
gapi and firebase:
const auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(() => {
return firebase.auth().signOut();
});Now you have the best of both worlds, the ability to make requests to any
Google API via gapi and an authenticated firebase client to communicate
with firebase APIs.
- Clone this repo locally.
- Build an Apps Script project from
./apps-script-project - Sign up for a Firebase app.
- Enable the "Google Drive API", "Script API", "Sheets API" for Firebase project.
- Find the OAuth Client ID firebase auto-created on setup and ensure your server's origin is listed in "Authorised JavaScript origins" (should be something like
http://localhost:8000, but depends on your server config). - Add the
init.jsfile to public/js which should content two constant
const FIREBASE_CONFIG = {
projectId: '...',
appId: '...',
databaseURL: '...',
storageBucket: '...',
locationId: '...',
apiKey: '...',
authDomain: '...',
messagingSenderId: '...',
};
const CLIENT_ID = '...';- Run your webserver
$> npx firebase serve - Open up your browser's dev console and check logging messages.
- Click login!