Google Sheets Authentication

Once you're displaying data from your Google Sheets in your application, you may want some users to be able to modify the data. Recall the users that you gave edit access to when you set sharing permissions on the sheets; they will now need to be validated prior to being able to edit the sheets.

To grant those permissions, we'll use the OAuth2 class to add OAuth support to the application. First, we'll need to import the GoogleSheet and OAuth2 classes and create the OAuth2 object:

import { GoogleSheet, OAuth2 } from '@grapecity/wijmo.cloud';
const SCOPES = [ 'https://www.googleapis.com/auth/userinfo.email' ];
const API_KEY = 'AIzaSyCvuXEzP57I5CQ9ifZDG2_K8M3nDa1LOPE';
const CLIENT_ID = '….apps.googleusercontent.com';
let auth = new OAuth2(API_KEY, CLIENT_ID, SCOPES, {
    error: (s, e) => {
        console.log(JSON.stringify(e.error, null, 2));

The SCOPES variable tells the server which services we want to use. In this case, we are only requesting the "email" scope, since that is all we are interested in. The information we'll be accessing belongs to the app, not to the user.

The APIKEY and CLIENTID allow OAuth to identify our application.

Now that we have an OAuth2 object, we can use it to provide a button so users can log in or out:

// 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) {
    } else {

Now that users can log in and out, we must listen to the userChanged event to update the button and the Spreadsheet's accessToken:

// 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 Spreadsheet access token
    gsNWind.accessToken = user ? s.accessToken : null;

Now users can click the button to log in. If the login succeeds, the server will use the accessToken to identify the user and grant or deny permissions so the users we selected when we shared the sheet will be able to edit the data.