• Stars
    star
    135
  • Rank 263,552 (Top 6 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An OAuth1 library for Google Apps Script.

OAuth1 for Apps Script

OAuth1 for Apps Script is a library for Google Apps Script that provides the ability to create and authorize OAuth1 tokens. This library uses Apps Script's new StateTokenBuilder and /usercallback endpoint to handle the redirects.

Note: OAuth1 for Google APIs is deprecated and scheduled to be shut down on April 20, 2015. For accessing Google APIs, use the Apps Script OAuth2 library instead.

Setup

This library is already published as an Apps Script, making it easy to include in your project. To add it to your script, do the following in the Apps Script code editor:

  1. Click on the menu item "Resources > Libraries..."
  2. In the "Find a Library" text box, enter the script ID 1CXDCY5sqT9ph64fFwSzVtXnbjpSfWdRymafDrtIZ7Z_hwysTY7IIhi7s and click the "Select" button.
  3. Choose a version in the dropdown box (usually best to pick the latest version).
  4. Click the "Save" button.

Alternatively, you can copy and paste the files in the /dist directory directly into your script project.

Callback URL

Before you can start authenticating against an OAuth1 provider, you usually need to register your application and retrieve the consumer key and secret. Often these registration screens require you to enter a "Callback URL", which is the URL that users will be redirected to after they've authorized the token. For this library (and the Apps Script functionality in general) the URL will always be in the following format:

https://script.google.com/macros/d/{SCRIPT ID}/usercallback

Where {SCRIPT ID} is the ID of the script that is using this library. You can find your script's ID in the Apps Script code editor by clicking on the menu item "File > Project properties".

Alternatively you can call the service's getCallbackUrl() method to view the exact URL that the service will use when performing the OAuth flow:

/**
 * Logs the callback URL to register.
 */
function logCallbackUrl() {
  var service = getService_();
  Logger.log(service.getCallbackUrl());
}

Usage

Using the library to generate an OAuth1 token has the following basic steps.

1. Create the OAuth1 service

The Service class contains the configuration information for a given OAuth1 provider, including it's endpoints, consumer keys and secrets, etc. This information is not persisted to any data store, so you'll need to create this object each time you want to use it. The example below shows how to create a service for the Twitter API.

Ensure the method is private (has an underscore at the end of the name) to prevent clients from being able to call the method to read your client ID and secret.

function getTwitterService_() {
  // 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 OAuth1.createService('twitter')
      // Set the endpoint URLs.
      .setAccessTokenUrl('https://api.twitter.com/oauth/access_token')
      .setRequestTokenUrl('https://api.twitter.com/oauth/request_token')
      .setAuthorizationUrl('https://api.twitter.com/oauth/authorize')
      // Set the consumer key and secret.
      .setConsumerKey('...')
      .setConsumerSecret('...')
      // 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());
}

2. Create a request token and direct the user to the authorization URL

Apps Script UI's are not allowed to redirect the user's window to a new URL, so you'll need to present the authorization URL as a link for the user to click. The service's authorize() method generates the request token and returns the authorization URL.

function showSidebar() {
  var twitterService = getTwitterService_();
  if (!twitterService.hasAccess()) {
    var authorizationUrl = twitterService.authorize();
    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 {
    // ...
  }
}

3. Handle the callback

When the user completes the OAuth1 flow, the callback function you specified for your service will be invoked. This callback function should pass its request object to the service's handleCallback() method, and show a message to the user.

function authCallback(request) {
  var twitterService = getTwitterService_();
  var isAuthorized = twitterService.handleCallback(request);
  if (isAuthorized) {
    return HtmlService.createHtmlOutput('Success! You can close this tab.');
  } else {
    return HtmlService.createHtmlOutput('Denied. You can close this tab');
  }
}

Note: In an Apps Script UI it's not possible to automatically close a window or tab, so you'll need to direct the user to close it themselves.

4. Make authorized requests

Now that the service is authorized you can use it to make reqests to the API. The service's fetch() method accepts the same parameters as the built-in UrlFetchApp.fetch() and automatically signs the requests using the OAuth1 token.

function makeRequest() {
  var twitterService = getTwitterService_();
  var response = twitterService.fetch('https://api.twitter.com/1.1/statuses/user_timeline.json');
  // ...
}

Compatiblity

This library was designed to work with any OAuth1 provider, but because of small differences in how they implement the standard it may be that some APIs aren't compatible. If you find an API that it does't work with, open an issue or fix the problem yourself and make a pull request against the source code.

3-legged OAuth

This library was primarily designed to support the 3-legged OAuth flow, where the end-user visits a web page to grant authorization to your application. The "Usage" section above describes how to configure the library for this flow.

2-legged OAuth

This library does not currently support the 2-legged OAuth flow, where tokens are generated but the user is not prompted to authorize access.

Be aware that many OAuth providers incorrectly use the term "2-legged" when describing their OAuth flow, when in reality they are using the 1-legged flow, which this library does support.

1-legged OAuth

This library supports the 1-legged OAuth flow, where the consumer key and secret are simply used to sign requests to the API endpoints, without the creation or exchanging of tokens. To use this flow, setup the service with a consumer key and secret (and optionally a token and token secret) and use it to call the API endpoint. See the Semantics3 sample and Yelp sample for some example usage.

Other features

Resetting the access token

If you have an access token set and need to remove it from the property store you can remove it with the reset() function. Before you can call reset you need to set the property store.

function clearService(){
  OAuth1.createService('twitter')
      .setPropertyStore(PropertiesService.getUserProperties())
      .reset();
}

Setting the request method and parameter location

OAuth1 providers may require that you use a particular HTTP method or parameter location when performing the OAuth1 flow. You can use the methods setMethod() and setParamLocation() to controls these settings.

More Repositories

1

md2googleslides

Generate Google Slides from markdown
TypeScript
4,435
star
2

apps-script-samples

Apps Script samples for Google Workspace products.
JavaScript
4,355
star
3

apps-script-oauth2

An OAuth2 library for Google Apps Script.
JavaScript
1,483
star
4

python-samples

🐍 Python samples for Google Workspace APIs
Python
1,154
star
5

android-samples

Android samples for Google Workspace APIs
Java
629
star
6

google-chat-samples

Chat Bot Samples for Google Chat.
JavaScript
461
star
7

node-samples

Node samples for Google Workspace APIs.
JavaScript
454
star
8

java-samples

☕ Java samples for Google Workspace APIs.
Java
315
star
9

browser-samples

Web samples for Google Workspace APIs
HTML
313
star
10

solutions

Community contributed solutions for Google Workspace
JavaScript
296
star
11

php-samples

PHP samples for Google Workspace APIs
PHP
283
star
12

add-ons-samples

Sample Google Workspace Add-ons
JavaScript
263
star
13

drive-quickeditors

A text editor for Android, iOS, and web illustrating how to open and save files with the Google Drive API
Objective-C
211
star
14

go-samples

Go samples for Google Workspace APIs
Go
209
star
15

drive-utils

Google Drive API utility functions.
JavaScript
188
star
16

dotnet-samples

.NET samples for Google Workspace APIs
C#
158
star
17

sheets-api-codelab

Use Google Sheets as your application's reporting tool
JavaScript
144
star
18

gmail-add-on-codelab

JavaScript
119
star
19

ruby-samples

💎 Ruby samples for Google Workspace APIs
Ruby
77
star
20

apps-script-intro-codelab

JavaScript
56
star
21

hangouts-chat-apps-script-codelab

JavaScript
55
star
22

cloud-search-samples

Samples for Google Cloud Search
Java
51
star
23

ml-integration-samples

This repo contains a collection of code samples and utilities for integrating Google Cloud AI & ML into Google Workspace.
JavaScript
40
star
24

gsuite-apis-intro

Python
30
star
25

chat-framework-nodejs

TypeScript
28
star
26

hubot-google-hangouts-chat

Hubot adapter for Google Chat.
JavaScript
23
star
27

google-docs-hast

Converts the JSON representation of a Google Docs document into an HTML abstract syntax tree (HAST).
TypeScript
23
star
28

slides-api

Learn How to Use the Google Slides API
JavaScript
22
star
29

awesome-workspace

Awesome list for Google Workspace.
TypeScript
17
star
30

gws-genai-addon-sample

A sample Google Workspace add-on for Gmail and Google Drive using Node.js and demonstrating how to use various Generative AI APIs
JavaScript
17
star
31

workspace-guardrails-ps-ca

16
star
32

gws-odo-addon

"Odo" is a Workspace Add-on that lets anyone easily demonstrate the capabilities of Workspace integrations for their customers, all without coding. Simply set the name + logo of the customer you are presenting to, configure Odo's behavior, and do a quick demo. This will help your customers visualize what Workspace extensibility can do for them.
JavaScript
16
star
33

ios-samples

iOS samples for Google Workspace APIs
Objective-C
13
star
34

appointment-scheduler-codelab

JavaScript
13
star
35

slides-advisor-add-on

JavaScript
11
star
36

.github

10
star
37

redriveapp

ReDriveApp (short for "Recommended" or "Replacement" DriveApp). AppsScript class that provides equivalent methods offered by the built-in DriveApp, but that does not require use of full '/drive' OAuth scope (which is a "Restricted" scope"). Instead, uses only these Recommended (non-sensitive) and/or Sensitive scopes.
JavaScript
8
star
38

docs-transcript-codelab

Java
7
star
39

python-oauth-token-manager

Python
5
star
40

.allstar

4
star
41

group-based-role-assignment-migration-util

Python
2
star
42

oneroster-integration-conformance-tests

Jupyter Notebook
2
star
43

python-calendar-insights-demo

Python
1
star