OAuth2

The OAuth2 class provides a robust interface for managing OAuth 2.0 authorization flows in Scripting. It supports standard authorization code flows, PKCE (Proof Key for Code Exchange), access token renewal, and customizable token handling.


Constructor

new OAuth2(options: {
  consumerKey: string
  consumerSecret: string
  authorizeUrl: string
  accessTokenUrl?: string
  responseType: string
  contentType?: string
})

Parameters

NameTypeRequiredDescription
consumerKeystringYesThe application's client ID or consumer key.
consumerSecretstringYesThe application's client secret.
authorizeUrlstringYesThe URL where the user will be redirected for authorization.
accessTokenUrlstringNoThe endpoint to request the access token. If omitted, authorizeUrl is used.
responseTypestringYesTypically "code" for the Authorization Code Grant flow.
contentTypestringNoContent type for token requests. Defaults to "application/x-www-form-urlencoded".

Throws

  • Error if the configuration is invalid or instantiation fails.

Properties

accessTokenBasicAuthentification: boolean

Enable this to use HTTP Basic authentication when exchanging the authorization code for an access token. Default is false.


allowMissingStateCheck: boolean

Disables CSRF protection based on state parameter validation. Use with caution. Default is false.


encodeCallbackURL: boolean

Encodes the callback URL when generating the authorization URL. Required by some providers. Default is true.


encodeCallbackURLQuery: boolean

Controls whether the entire query string is encoded. Some services (e.g., Imgur) require this to be false. Default is true.


Methods

authorize(options): Promise<OAuthCredential>

Initiates the OAuth2 authorization flow, opening a browser window for the user to log in and grant permissions.

authorize(options: {
  callbackURL?: string
  scope: string
  state: string
  parameters?: Record<string, any>
  headers?: Record<string, string>
} & ({
  codeVerifier: string
  codeChallenge: string
  codeChallengeMethod: string
} | {
  codeVerifier?: never
  codeChallenge?: never
  codeChallengeMethod?: never
})): Promise<OAuthCredential>

Parameters

NameTypeRequiredDescription
callbackURLstringNoCustom redirect URI. Default is scripting://oauth_callback/{current_script_encoded_name}.
scopestringYesSpace-separated list of requested scopes.
statestringYesA unique string used to prevent CSRF attacks.
parametersRecord<string, any>NoExtra query parameters to send in the authorization request.
headersRecord<string, string>NoExtra headers to send in the request.
codeVerifierstringConditionalRaw random string used in PKCE flow.
codeChallengestringConditionalHashed version of the code verifier.
codeChallengeMethod"plain" | "S256"ConditionalHashing method for code challenge. Default is "S256".

Returns

  • A Promise that resolves to an OAuthCredential object containing tokens and metadata.

Throws

  • Error if the user denies authorization or a network/response error occurs.

Example

const oauth = new OAuth2({
  consumerKey: 'your-client-id',
  consumerSecret: 'your-client-secret',
  authorizeUrl: 'https://provider.com/oauth/authorize',
  accessTokenUrl: 'https://provider.com/oauth/token',
  responseType: 'code'
})

const credential = await oauth.authorize({
  scope: 'profile email',
  state: 'secure_random_state',
  callbackURL: Script.createOAuthCallbackURLScheme('my_oauth_script')
})

console.log(credential.oauthToken)

renewAccessToken(options): Promise<OAuthCredential>

Exchanges a refresh token for a new access token from the provider.

renewAccessToken(options: {
  refreshToken: string
  parameters?: Record<string, any>
  headers?: Record<string, string>
}): Promise<OAuthCredential>

Parameters

NameTypeRequiredDescription
refreshTokenstringYesThe refresh token previously obtained.
parametersRecord<string, any>NoAdditional POST body parameters.
headersRecord<string, string>NoAdditional headers for the request.

Returns

  • A Promise that resolves to an updated OAuthCredential object.

Throws

  • Error if the refresh fails due to expired or revoked tokens.

Example

const newCredential = await oauth.renewAccessToken({
  refreshToken: previous.oauthRefreshToken
})

console.log(newCredential.oauthToken)

OAuthCredential Type

The OAuthCredential object contains all relevant information from a successful OAuth2 transaction.

type OAuthCredential = {
  oauthToken: string
  oauthTokenSecret: string
  oauthRefreshToken: string
  oauthTokenExpiresAt: number | null
  oauthVerifier: string
  version: string
  signatureMethod: string
}

Field Descriptions

FieldTypeDescription
oauthTokenstringAccess token to authorize requests to the API.
oauthTokenSecretstringToken secret for request signing (used in OAuth1.0-like flows).
oauthRefreshTokenstringToken used to refresh the access token.
oauthTokenExpiresAtnumber | nullExpiration time in Unix timestamp (ms). null if no expiration.
oauthVerifierstringVerifier used for PKCE validation.
versionstringOAuth version (e.g., "2.0").
signatureMethodstringMethod used to sign requests (e.g., "HMAC-SHA1", "PLAINTEXT").

Best Practices

  • Always verify state to protect against CSRF attacks unless explicitly disabled.
  • Use Script.createOAuthCallbackURLScheme(name) to generate script-specific callback URLs.
  • Securely store the oauthRefreshToken if long-term access is needed.
  • Consider using PKCE for enhanced security, especially in public clients.