DEV Community

Toni-Jan Keith Monserrat
Toni-Jan Keith Monserrat

Posted on

How to build a server that authenticates requests from Google Appscript using OpenID

A simple way to authenticate your requests coming from Google Workspace Appscript is to use OpenID.

To do that, call the getIdentityToken from ScriptApp.

// Appscript.gs
const oAuthToken = ScriptApp.getIdentityToken()
Enter fullscreen mode Exit fullscreen mode

And then put that as part of the request. In this example, I put it as a bearer token using the authorization header.

// Appscript.gs
const request = {
  method: 'POST',
  contentType: 'application/json',
  payload: JSON.stringify({
    ...
  }),
  headers: {
    Authorization: `Bearer ${oAuthToken}`
  } 
}
const results = UrlFetchApp.fetch(url, request);  
Enter fullscreen mode Exit fullscreen mode

On the backend, process the header and get the token by getting the email, if it is verified, the host, and the issuer. You can then use these data to verify the user.

// backend.js - middleware to process the header
  const { headers } = request;
  const { authorization } = headers;

  // if there is no authorization header, return 403
  if (!authorization) return response.unauthorized();

  // get the token by using "Bearer " as the splitting token
  const [, idToken] = authorization.split('Bearer ');

  // the OpenID is a JWT with a header and body.
  // we get the body and make it as a UTF8 string
  const [, item] = idToken.split('.');
  const buff = Buffer.from(item, 'base64');
  const jsonText = buff.toString();

  try {
    const {  
      email, 
      hd: host, 
      iss: issuer, 
      email_verified: emailVerified 
    } = JSON.parse(jsonText);

    // check email here
    if (!email || !emailVerified) return response.unauthorized();

    // check host here
    if (!host) return response.unauthorized();

    // issuer must be accounts.google.com
    if (issuer !== 'https://accounts.google.com') return response.unauthorized();

    // process email by checking it on db
    ...
  } catch (error) { ... }
Enter fullscreen mode Exit fullscreen mode

Enjoy!

Top comments (0)