An example of how to use GAPI and Firebase Auth together to authenticate users and talk to Google APIs.
If you are trying to use Google's JavaScript Library to query Google APIs (e.g. Google Analytics), 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.
- Sign up for a Firebase app.
- Enable the "Analytics 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). - Search the source code for
//OVERWRITE ME
and fill in your relevant configuration. - Run your webserver (Python's
SimpleHTTPServer
is a great choice) and open the page. - Open up your browser's dev console and check logging messages.
- Click login!