apps-script-oauth2
An OAuth2 library for Google Apps Script.
AI Summary
OAuth2 for Apps Script
GAS library to acquire and refresh OAuth2 tokens
Target Users
Intermediate developers building internal tools or add-ons needing secure OAuth2 with external APIs
Problems Solved
Simplifies OAuth2 authorization, redirects, and token management in GAS
Tags
Main Features
Chained configuration
Configure endpoints, scopes, and params via createService and set* for a concise OAuth2 flow
Token storage/refresh
Persist tokens with PropertiesService, auto-refresh, and reduce quotas/races via Cache/Lock
Redirect handling
Simplifies redirect and callback via getRedirectUri, /usercallback, and state token handling
Multiple grant flows
Supports auth code, service accounts (JWT), and client_credentials grant types
Flexible tuning
Adjust token format/method, headers, and payload handler; add extra token headers as needed
Usage Examples
Basic usage (Drive API example)
The following snippets are taken from the README.
function getDriveService_() {
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
return OAuth2.createService('drive')
// Set the endpoint URLs, which are the same for all Google services.
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the client ID and secret, from the Google Developers Console.
.setClientId('...')
.setClientSecret('...')
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
// Set the scopes to request (space-separated for Google services).
.setScope('https://www.googleapis.com/auth/drive')
// Below are Google-specific OAuth2 parameters.
// Sets the login hint, which will prevent the account chooser screen
// from being shown to users logged in with multiple accounts.
.setParam('login_hint', Session.getEffectiveUser().getEmail())
// Requests offline access.
.setParam('access_type', 'offline')
// Consent prompt is required to ensure a refresh token is always
// returned when requesting offline access.
.setParam('prompt', 'consent');
}function showSidebar() {
var driveService = getDriveService_();
if (!driveService.hasAccess()) {
var authorizationUrl = driveService.getAuthorizationUrl();
var template = HtmlService.createTemplate(
'<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a>. ' +
'Reopen the sidebar when the authorization is complete.');
template.authorizationUrl = authorizationUrl;
var page = template.evaluate();
DocumentApp.getUi().showSidebar(page);
} else {
// ...
}
}function authCallback(request) {
var driveService = getDriveService_();
var isAuthorized = driveService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}function makeRequest() {
var driveService = getDriveService_();
var response = UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files?maxResults=10', {
headers: {
Authorization: 'Bearer ' + driveService.getAccessToken()
}
});
// ...
}function logout() {
var service = getDriveService_()
service.reset();
}