Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Jun 11, 2025. It is now read-only.

An OAuth1 library for Google Apps Script.

License

NotificationsYou must be signed in to change notification settings

googleworkspace/apps-script-oauth1

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

Note: OAuth1 for Google APIs isdeprecated and scheduledto be shut down on April 20, 2015. For accessing Google APIs, use theApps Script OAuth2 library instead.

Setup

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

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

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

Callback URL

Before you can start authenticating against an OAuth1 provider, you usually needto register your application and retrieve the consumer key and secret. Oftenthese registration screens require you to enter a "Callback URL", which is theURL that users will be redirected to after they've authorized the token. Forthis library (and the Apps Script functionality in general) the URL will alwaysbe 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. Youcan find your script's ID in the Apps Script code editor by clicking on the menuitem "File > Project properties".

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

/** * Logs the callback URL to register. */functionlogCallbackUrl(){varservice=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 givenOAuth1 provider, including it's endpoints, consumer keys and secrets, etc. Thisinformation is not persisted to any data store, so you'll need to create thisobject each time you want to use it. The example below shows how to create aservice for the Twitter API.

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

functiongetTwitterService_(){// 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.returnOAuth1.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, soyou'll need to present the authorization URL as a link for the user to click.The service'sauthorize() method generates the request token and returns theauthorization URL.

functionshowSidebar(){vartwitterService=getTwitterService_();if(!twitterService.hasAccess()){varauthorizationUrl=twitterService.authorize();vartemplate=HtmlService.createTemplate('<a href="<?= authorizationUrl ?>">Authorize</a>. '+'Reopen the sidebar when the authorization is complete.');template.authorizationUrl=authorizationUrl;varpage=template.evaluate();DocumentApp.getUi().showSidebar(page);}else{// ...}}

3. Handle the callback

When the user completes the OAuth1 flow, the callback function you specifiedfor your service will be invoked. This callback function should pass itsrequest object to the service'shandleCallback() method, and show a messageto the user.

functionauthCallback(request){vartwitterService=getTwitterService_();varisAuthorized=twitterService.handleCallback(request);if(isAuthorized){returnHtmlService.createHtmlOutput('Success! You can close this tab.');}else{returnHtmlService.createHtmlOutput('Denied. You can close this tab');}}

Note: In an Apps Script UI it's not possible to automatically close a windowor 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'sfetch() method accepts the same parameters as the built-inUrlFetchApp.fetch()and automatically signs the requests using the OAuth1 token.

functionmakeRequest(){vartwitterService=getTwitterService_();varresponse=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 smalldifferences in how they implement the standard it may be that some APIsaren't compatible. If you find an API that it does't work with, open an issue orfix the problem yourself and make a pull request against the source code.

3-legged OAuth

This library was primarily designed to support the3-legged OAuth flow, wherethe 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 the2-legged OAuth flow, wheretokens are generated but the user is not prompted to authorize access.

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

1-legged OAuth

This library supports the1-legged OAuth flow, where theconsumer 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 theservice with a consumer key and secret (and optionally a token and token secret)and use it to call the API endpoint. See theSemantics3 sample andYelp samplefor some example usage.

Other features

Resetting the access token

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

functionclearService(){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 parameterlocation when performing the OAuth1 flow. You can use the methodssetMethod()andsetParamLocation() to controls these settings.

About

An OAuth1 library for Google Apps Script.

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors8


[8]ページ先頭

©2009-2025 Movatter.jp