apps-script-oauth2
An OAuth2 library for Google Apps Script.
AI Summary
Apps Script OAuth2 Library
A library that streamlines OAuth2 authentication when calling external APIs from Google Apps Script
Target Users
Intermediate-to-advanced Apps Script developers building internal tools or add-ons who want to simplify OAuth2 implementation for external APIs
Problems Solved
Implementing OAuth2 flows in Apps Script requires complex token management and refresh handling, making external API integration tedious
Tags
Main Features
Configure-only OAuth2 flow
Simply define authorization URL, token URL and scopes with createService to automatically handle Authorization Code, Client Credentials and other flows
Automatic token storage & refresh
Stores access and refresh tokens in Script/User Properties and refreshes them automatically when expired
Includes many service samples
Provides ready-to-use configuration examples for GitHub, Slack, Dropbox and more, reducing setup time
Caching, logging and advanced settings
Exposes APIs to set token cache duration, UrlFetchApp timeouts, logging outputs and other fine-grained options
Manage multiple services in one script
By passing different names to createService you can maintain multiple independent OAuth2 connections within a single script
Usage Examples
Minimal example: Calling the GitHub API with OAuth2
/**
* Build an OAuth2 service for GitHub
*/
function getGitHubService() {
return OAuth2.createService('github')
// Authorization endpoint
.setAuthorizationBaseUrl('https://github.com/login/oauth/authorize')
// Token endpoint
.setTokenUrl('https://github.com/login/oauth/access_token')
// Client credentials issued in GitHub Developer Settings
.setClientId('YOUR_CLIENT_ID')
.setClientSecret('YOUR_CLIENT_SECRET')
// Callback function name in this GAS project
.setCallbackFunction('authCallback')
// Store tokens in User Properties
.setPropertyStore(PropertiesService.getUserProperties())
// Requested scope
.setScope('repo');
}
/**
* Receive the OAuth2 redirect and store the token
*/
function authCallback(request) {
const service = getGitHubService();
const authorized = service.handleCallback(request);
return HtmlService.createHtmlOutput(authorized ? 'Success!' : 'Denied');
}
/**
* After authorization, call the GitHub REST API
*/
function listMyRepos() {
const service = getGitHubService();
if (service.hasAccess()) {
// Call the API with the access token
const response = UrlFetchApp.fetch('https://api.github.com/user/repos', {
headers: { Authorization: 'Bearer ' + service.getAccessToken() }
});
Logger.log(response.getContentText());
} else {
// First run: output the authorization URL
Logger.log('Open the following URL and re-run the script: %s', service.getAuthorizationUrl());
}
}
Paste the code, set your client ID/secret, run listMyRepos()
and authorize the script to see your repository list in the log.