5.20203.748
5.20203.748

Authenticating Firestore Users

For authentication, the Firestore REST API accepts either a Firebase Authentication ID token or a Google Identity OAuth 2.0 token.

  • If you use a Firebase ID token, Firestore uses Cloud Firestore Security Rules to determine if a request is authorized. This is the preferred option since it leverages the Firestore Security Rules (which are flexible and powerful), and because it is the only option supported by the Snapshot class.
  • If you use a Google Identity OAuth 2.0 token, Firestore uses Cloud Identity and Access Management (IAM) to determine if a request is authorized. This option bypasses the Firestore Security Rules and uses the authorizations granted to users by the IAM administrator. This is like the authentication used by the GoogleSheet class.

In our example, we will use a Firebase ID token.

We'll first need to import the Firestore and OAuth2 classes:

import { Firestore, OAuth2 } from '@grapecity/wijmo.cloud';

We'll then create our OAuth2 object using the Firebase ID token that we generated:

const CLIENT_ID = '60621001861-h0u4ek4kmd3va9o2bubhq9ean0bgrhu2.apps.googleusercontent.com';
const SCOPES = [ 'https://www.googleapis.com/auth/userinfo.email' ];
let auth = new OAuth2(API_KEY, CLIENT_ID, SCOPES);

// button to log in/out
let oAuthBtn = document.getElementById('auth_btn');

// click button to log user in or out
oAuthBtn.addEventListener('click', () => {
    if (auth.user) {
        auth.signOut();
    } else {
        auth.signIn();
    }
});

To finish authentication, we must also apply the idToken to the Firestore object when the user changes (to use an OAuth2 token, we would set the accessToken property instead):

// update button/sheet state when user changes  
auth.userChanged.addHandler(s => {  
    let user = s.user;  

    // update button caption  
    oAuthBtn.textContent = user ? 'Sign Out' : 'Sign In';  

    // update Firestore ID token  
    fsNWind.idToken = user ? s.idToken : null;  
});