Skip to content

Instantly share code, notes, and snippets.

@baflo
Last active September 29, 2017 09:26
Show Gist options
  • Save baflo/909a140c0490a65108b8608201dc637a to your computer and use it in GitHub Desktop.
Save baflo/909a140c0490a65108b8608201dc637a to your computer and use it in GitHub Desktop.

Server accounts for Google API

Servers can use any (most?) authentication ways that can also be used by clients. However, those usually involve authentication web pages,redirects, etc. Quite unpractical for your server app. So we may use Service Accounts as well and authenticate with a single JWT (JSON Web Token) file.

Hence, we need to create a Service Account in the cloud console. This service account has its own realm, i.e. access to other users' data is not immediately possible.

It is, however, possible to impersonate other users if we are running on an own domain, e.g. using the GSuite. In that case, a service account may be set up to impersonate any other user in that domain.

Baisc steps

Preparation

  • Choose the domain you want to use
  • Choose the scopes you need (can be found here)
  • Create project (or select existing one)
  • Go to API & Services -> Dashboard
    • activate the APIs you want to use
  • Go to access control
    • Create Service Account Key
    • Ignore json file JWT
  • Go to IAM & Administration -> Service Accounts
    • Click menu after the just created service account and edit
    • Activate domainwide delegation
    • Click menu and create json keys (safe it securely!)
  • In Security -> Advanced Settings, select API Client Access
  • Add newly created service account as client
  • Enter the pre-selected scopes

In your app

  • Use code from below
  • in new google.auth.JWT, the last parameter names the user you want to impersonate. Enter his/her username.
import * as fs from 'fs';
import * as path from 'path';
const google = require('googleapis');
// Google API client data
const GOOGLE_SERVICE_CLIENT_KEY_FILENAME = process.enc.GOOGLE_SERVICE_CLIENT_KEY_FILENAME || path.join(__dirname, './service-client-key.json');
// generate a url that asks permissions for Google+ and Google Calendar scopes
const scopes: string[] = [
'https://www.googleapis.com/auth/drive'
];
// Create service client
const JWT = google.auth.JWT;
const jwtKey = require(SERVICE_CLIENT_KEY_FILENAME);
const jwtClient = new JWT(
jwtKey.client_email,
null,
jwtKey.private_key,
scopes,
'user@userland.com',
);
jwtClient.authorize((err: null | Error, tokens: any) => {
if (err) {
console.log(err);
return;
}
jwtClient.setCredentials(tokens);
google.options({
auth: jwtClient
});
});
export { google };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment