This library creates and refreshes OAuth2 tokens inside Apps Script, routing user authorization through the platform usercallback endpoint.
Overview
OAuth2 for Apps Script is a library published for Google Apps Script projects that need to authorize against external OAuth2 providers. It wraps creation of authorization URLs, callback handling, access-token retrieval, refresh, and logout reset in a service object you configure per provider.
Redirects use Apps Script StateTokenBuilder and the standard usercallback URL format tied to your script ID, which you register as the redirect URI with the provider. Many Google APIs may be reachable through built-in or advanced Apps Script services without this library, using ScriptApp.getOAuthToken instead.
Typical usage builds a private OAuth2Service with endpoints and client credentials, sends the user to getAuthorizationUrl, handles handleCallback in a web callback, then attaches the bearer token to UrlFetchApp requests. Token persistence uses PropertiesService or CacheService with optional LockService to avoid refresh races in add-ons.
Advanced configuration covers token payload formats, extra headers, non-POST token endpoints, custom payload handlers, service-account JWT flows including domain-wide delegation, and alternate grant types such as client credentials.
Key features
- OAuth2 authorization URL generation
- Apps Script usercallback redirect handling
- Access token refresh and reset
- Properties and cache backed token storage
- Locking around concurrent token refresh
- Service account JWT authorization flow
- Support for custom grant types and headers
- Published Apps Script library distribution
Use cases
- Third-party API access from Workspace automations
- Add-on OAuth for non-Google providers
- Service account calls with domain-wide delegation
- Persisted tokens for scheduled script triggers