Giter VIP home page Giter VIP logo

apps-script-oauth1's People

Contributors

alephyud avatar alniss avatar dependabot[bot] avatar googleworkspace-bot avatar grant avatar labnol avatar sblom avatar sqrrrl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

apps-script-oauth1's Issues

[SyncRepoSettings bot] - Invalid config file

Failed to validate the config schema at '.github/sync-repo-settings.yaml': [
{
"instancePath": "/permissionRules/1/permission",
"schemaPath": "#/properties/permissionRules/items/properties/permission/enum",
"keyword": "enum",
"params": {
"allowedValues": [
"pull",
"push",
"admin"
]
},
"message": "must be equal to one of the allowed values"
}
]

Schema can be found at https://github.com/googleapis/repo-automation-bots/blob/main/packages/sync-repo-settings/src/schema.json

TripIt: 1) call oauth_callback to authorize URL, 2) error message: state token is invalid or has expired

I am trying to use the OAuth1 library for TripIt.

Issue 1:

By default, the authorization URL that is created by the library is:
https://www.tripit.com/oauth/authorize?oauth_token=7af4...96c

But TripIt expects the URL to be:
https://www.tripit.com/oauth/authorize?oauth_token=7af4...96c&oauth_callback=https://script.google.com/macros/d/MrG...b6R/usercallback

Q: is there a way to automatically create the correct URL? I now add the callback manually.

Issue 2:

With the correct URL I get a TripIt authentication page. When I click Allow the Google Apps Script macro page is opened, with the error message: The state token is invalid or has expired. Please try again.

The URL of that macro page:
https://script.google.com/macros/d/MrG...b6R/usercallback?oauth_token=7af...96c

Q: what is the cause / fix of this?

The code I use to create the service:

  return OAuth1.createService('tripit')
      .setRequestTokenUrl('https://api.tripit.com/oauth/request_token')
      .setAuthorizationUrl('https://www.tripit.com/oauth/authorize')
      .setAccessTokenUrl('https://api.tripit.com/oauth/access_token')
      .setConsumerKey('73b...458')
      .setConsumerSecret('2a7...a5d')
      .setProjectKey('MrG...b6R')
      .setCallbackFunction('authCallback')
      .setPropertyStore(PropertiesService.getUserProperties())

The TripIt API documention:
http://tripit.github.io/api/doc/v1/index.html#authentication_section

Thanks in advance for any suggestions!

OAUTH Token undefined

Hi

I'm sure this is my ineptitude that's causing this issue but maybe you can help.

When I call the OpenSidebar() function to authorize the application, the link shown does not have a oauth token defined. Instead of including the token, the URL is as follows:

https://developer.health.nokia.com/account/authorize?oauth_token=undefined

Here is my code (with the consumer keys removed).

function getNokiaService() {
  return OAuth1.createService('nokia')
    .setAccessTokenUrl('https://developer.health.nokia.com/account/access_token')
    .setRequestTokenUrl('https://developer.health.nokia.com/account/request_token')
    .setAuthorizationUrl('https://developer.health.nokia.com/account/authorize')

    .setConsumerKey('')
    .setConsumerSecret('')
    
    .setCallbackFunction('authCallback')
  
    .setPropertyStore(PropertiesService.getUserProperties());
}

function showSidebar() {
  var nokiaService = getNokiaService();
  if (!nokiaService.hasAccess()) {
    var authorizationUrl = nokiaService.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();
    SpreadsheetApp.getUi().showSidebar(page);
  } else {
    
  }
}

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

function syncNokiaData() {
  var nokiaService = getNokiaService();
  var response = nokiaService.fetch('https://api.health.nokia.com/measure?action=getmeas');
  return response;
}

Error starting OAuth flow on Trello

Using the provided code, importing the library (as resource) and updating CONSUMER_KEY and CONSUMER_SECRET give me this error.
Error starting OAuth flow: {} (línea 330, archivo "Service", proyecto "OAuth1")
Any idea what is happening? Using URL with tokens boards in JSON are returned fine.
Thanks!

Trello Invalid Signature

I have a Google Apps Script program that Does Stuff to Trello cards (and other things) based on external outputs. In this case, we cycle through cards in a certain lane and download their attachments to Google Drive folders indicated in a custom field on each card, then mark the card to say the files have been downloaded. Pretty simple stuff, except Trello's API now doesn't let you directly download files without authentication. While most of the operations you can do in the API just let you pass key and token as URL parameters, downloading a file makes you set up Oauth1 to initiate the GET request. And for the life of me I can't get it to work. I'm using the GAS Oauth1 library and the Trello sample for the library from here:

https://github.com/googleworkspace/apps-script-oauth1/blob/master/samples/Trello.gs

When I run the code, I get "Error starting OAuth flow: Invalid Signature." Here's the contents of the connection object:

{authorizationUrl_=https://trello.com/1/OAuthAuthorizeToken?scope=read,write,
accessTokenUrl_=https://trello.com/1/OAuthGetAccessToken,
consumerSecret_=[REDACTED],
paramLocation_=auth-header,
requestTokenUrl_=https://trello.com/1/OAuthGetRequestToken,
scriptId_=[REDACTED],
consumerKey_=[REDACTED],
method_=get,
serviceName_=trello,
propertyStore_=ScriptProperties,
signatureMethod_=HMAC-SHA1,
callbackFunctionName_=authCallback_Trello,
oauthVersion_=1.0a}

It's not the library, because I can authenticate and post to Twitter through OAuth fine using the same library from the same GAS project. But the error is so vague I can't diagnose what the issue might be. I've tried a variety of different connection scripts but can't get any closer to figuring it out.

Goodreads OAuth Problems

I'm trying to connect my app to Goodreads, but I keep getting an error.

The state token is invalid or has expired. Please try again.

The callback URL I see in the window with the error has two question marks in it, instead of another ampersand...

https://script.google.com/macros/d/{Script ID}/usercallback?state={Really Long State String}?oauth_token={Oauth Token}&authorize=1

edit: I only get the state in the URL if I set .setOAuthVersion('1.0'). If I don't set the OAuthVersion, I don't get the state in the callback URL, but I get the same error (state token is invalid or has expired).

Is this something I can fix in a setting on my side with an extra parameter, or is this on Goodreads?

OAuth1 not working in Chrome V8 Engine

Hello,

When using the new Apps Script runtime (Google Chrome V8), the library does not work anymore.

For example:

var CONSUMER_KEY = '...';
var CONSUMER_SECRET = '...';

/**
 * Authorizes and makes a request to the Twitter API.
 */
function run() {
  var service = getService();
  if (service.hasAccess()) {  // Error occured!
    Logger.log('Authorized.');
  } 
} 

function getService() {
  return OAuth1.createService('Twitter')
      .setAccessTokenUrl('https://api.twitter.com/oauth/access_token')
      .setRequestTokenUrl('https://api.twitter.com/oauth/request_token')
      .setAuthorizationUrl('https://api.twitter.com/oauth/authorize')
      .setConsumerKey(CONSUMER_KEY)
      .setConsumerSecret(CONSUMER_SECRET)
      .setPropertyStore(PropertiesService.getScriptProperties());
}

I got this error :

Property store is required.
    at [unknown function](OAuth1:1058:7)
    at validate_(OAuth1:1055:23)
    at Service_.getToken_(OAuth1:625:3)
    at Service_.hasAccess(OAuth1:409:20)
    at run(Code:10:15)

I have found _.isEmpty() returns true when ScriptPropertyStore(has only a non-enumerable property).

https://github.com/gsuitedevs/apps-script-oauth1/blob/d804872cac7ee5e062d39e1060733c472f209b9f/src/Utilities.gs#L58

Thank your for your support !

Not working anymore?

Its look that this isn't working anymore:

{"errors":[{"code":215,"message":"Bad Authentication data."}]}

Its say something at lines 433 at file "Service"

It was working before fine (~ 2 years ago), but now not anymore. I'm using for Twitter btw.

Modify Callback Function?

Hi,

I'm trying to use this library to access a third party API through google apps script but I am running into a problem where the default callback function that the package sets returns an error. The third party API requires a specific input for the callback function. Is there anyway to modify it?

Thanks

QuickBooks error when querying with =

I see this error happening with QuickBooks when querying with = (%3D)

For the URL https://quickbooks.api.intuit.com/v3/company/123145856926847/reports/ProfitAndLoss?accounting_period%3D'Cash'

I get the below error
Status : 401.0,
Response : "\n\n \n \n message=ApplicationAuthenticationFailed; errorCode=003200; statusCode=401\n \n \n\n"

I am blocked with this, appreciate if you could help me to resolve this issue.
thanks

Note : I saw a related issue closed earlier, however I still get this issue in the latest version (13)

oauth1 - Twitter: I cannot get Friendship_Lookup functioning...Could not authenticate you

I am migrating towards the github oauth1 google script class specification. I got the call working for posting, but I get an error when trying to get it functioning with friendship_lookup.

Error: "Request failed for https://api.twitter.com/1.1/friendships/lookup.json returned code 401. Truncated server response: {"errors":[{"code":32,"message":"Could not authenticate you."}]} (use muteHttpExceptions option to examine full response) (line 423, file "Service", project "OAuth1")"

Question: is it possible to post example code for friendships lookup, which I can copy?

THANK YOU!
(Debugging, trying, analyzing took already over 15 hours... hope you, or somebody can help!)

[email protected]

Code:

function friendship_lookUpTest_ITryConformGithubOauth1spec() {
var service = getService();
if (service.hasAccess()) {
var url = 'https://api.twitter.com/1.1/friendships/lookup.json';
var payload = {
screen_name: 'twitterapi'
};
var response = service.fetch(url, {
method: 'GET',
payload: payload
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
} else {
var authorizationUrl = service.authorize();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
}

Certain characters in twitter status break authentication

Hello,

I'm attempting to use this library to update Twitter, sort of like in the example code. It works most of the time, unless the status body contains certain characters: !, *, (, ), and a handful of others. Whereas it works normally without those characters, attempting to send a tweet with an exclamation point cause Twitter to return its error code "32", "Could not authenticate you."

This may be the same underlying problem discussed but never addressed in this Issue: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3046 So it's possible that the solution may lie deeper than this library, but I thought I'd bring it up here just in case.

I've tried various workarounds like replacing ! with %21 in the url string, but all to no avail. Any suggestions? I can provide sample code to reproduce if necessary.

Thanks,
Zach

Can I pass Basic Auth of request url ?

Hi,

thank you for your providing such good tool.

I'm now trying to use this for Wordpress Rest API.
But my website is in staging environment, so locked by Basic Auth.

Is there any good way to pass through Basic Auth to get request token.

Thanks!

Authentication failed with Quickbooks Online POST OAUTH 1.0?

I've hit another brick wall and again I'm not sure if I'm doing something wrong. This is with version 7.

I am trying to post data to the Quickbooks API v3 to create a new bill but it returns an authentication error. They utilize OAuth 1.0.

Request URL:
https://quickbooks.api.intuit.com/v3/company/[company id]/bill

var CONSUMER_KEY = '***********';
var CONSUMER_SECRET = '***********';
var PROJECT_KEY = '***********';

function QBPost(url, payload) {
  var service = getQBService();
  var options = {
        "payload" : payload,   
        "headers" : { "Accept" : "application/json" },
        "muteHttpExceptions" : true
      };
  if (service.hasAccess()) {
    var response = service.setMethod("post").fetch(url, options);
    return response;

  } else {
    var authorizationUrl = service.authorize();
    return "ERROR - Please visit the following URL and then re-run the script: " + authorizationUrl;
  }
}

function postQBService() {
  var service = OAuth1.createService('QBPost');
  service.setAccessTokenUrl('https://oauth.intuit.com/oauth/v1/get_access_token');
  service.setRequestTokenUrl('https://oauth.intuit.com/oauth/v1/get_request_token');
  service.setAuthorizationUrl('https://appcenter.intuit.com/Connect/Begin');
  service.setOAuthVersion('1.0');
  service.setConsumerKey(CONSUMER_KEY);
  service.setConsumerSecret(CONSUMER_SECRET);
  service.setProjectKey(PROJECT_KEY);
  service.setCallbackFunction('authCallbackPost');
  service.setPropertyStore(PropertiesService.getScriptProperties());
  return service;
}

function authCallbackPost(request) {
  var service = postQBService();
  service.setOAuthVersion('1.0');
  var isAuthorized = service.handleCallback(request);
  if (isAuthorized) {
    return HtmlService.createHtmlOutput('Success! You can close this page.');
  } else {
    return HtmlService.createHtmlOutput('Denied. You can close this page');
  }
}

This generates the following Param in the service.gs script to use with fetch:

{payload:"{ \"SalesTermRef\": { \"value\": \"18\" }, \"DueDate\": \"2015-04-29\", \"domain\": \"QBO\", \"sparse\": false, \"DocNumber\": \"161321\", \"TxnDate\": \"2015-03-30\", \"CurrencyRef\": { \"value\": \"USD\", \"name\": \"United States Dollar\" }, \"PrivateNote\": \"test\", \"Line\": [ { \"Id\": \"1\", \"Description\": \"\", \"Amount\": \"88\", \"DetailType\": \"AccountBasedExpenseLineDetail\", \"AccountBasedExpenseLineDetail\": { \"AccountRef\": { \"value\": \"\" }, \"BillableStatus\": \"NotBillable\", \"TaxCodeRef\": { \"value\": \"NON\" } } } ], \"VendorRef\": { \"value\": \"372\" } } ", method:"post", 'Content-Type':"application/json", headers:{Accept:"application/json", Authorization:"OAuth oauth_consumer_key=\"**********\", oauth_nonce=\"DznLGZpccDsrJtrGFJVAok1nnwT5FKQ1\", oauth_signature=\"L7tYX8VWCRmLScafQbyRrtrQezs%3D\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"1429543832\", oauth_token=\"**********\", oauth_version=\"1.0\""}, muteHttpExceptions:true}

Which then returns the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<IntuitResponse time="2015-04-17T12:23:32.973-07:00" 
    xmlns="http://schema.intuit.com/finance/v3">
    <Fault type="AUTHENTICATION">
        <Error code="3200">
            <Message>message=ApplicationAuthenticationFailed; errorCode=003200; statusCode=401</Message>
        </Error>
    </Fault>
</IntuitResponse>

I pulled the tokens and and tried using the same ones in postman:

POST /v3/company/701648525/bill HTTP/1.1
Host: quickbooks.api.intuit.com
Content-Type: application/json
Authorization: OAuth oauth_consumer_key="**********",oauth_token="**********",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1429544377",oauth_nonce="UbUcDy",oauth_version="1.0",oauth_signature="NPHE1VPGtthKRhKPJ42mnDkAeXs%3D"
Cache-Control: no-cache
Postman-Token: a7067fd1-3fc1-4e18-2fda-4128fc5a1c98

{         "SalesTermRef": {           "value": "18"         },         "DueDate": "2015-04-29",         "domain": "QBO",         "sparse": false,         "DocNumber": "161321",         "TxnDate": "2015-03-30",         "CurrencyRef": {           "value": "USD",           "name": "United States Dollar"         },         "PrivateNote": "test",         "Line": [ {             "Id": "1",             "Description": "",             "Amount": "88",             "DetailType": "AccountBasedExpenseLineDetail",             "AccountBasedExpenseLineDetail": {               "AccountRef": {                 "value": "185"               },               "BillableStatus": "NotBillable",               "TaxCodeRef": {                 "value": "NON"               }             } }         ],         "VendorRef": {           "value": "372"         } }



and got the following:

{
"Fault": {
"Error": [
{
"Message": "Duplicate Document Number Error",
"Detail": "Duplicate Document Number Error : You must specify a different number. This number has already been used.",
"code": "6140",
"element": ""
}
],
"type": "ValidationFault"
},
"time": "2015-04-20T08:42:50.274-07:00"
}

Which is exactly what I am expecting as a response from their API.

I have also tried manually setting the tokens with ones I have tested and know work:

function settoken(){
 var x = {'public':"xxxxxxxxxx", secret:"xxxxxxxxxx", type:"access"};
  var service = postQBService();
  service.saveToken_(x);
}

But that doesn't seem to have any impact on the result.

Unable to Pass Header Parameters?

Am I doing something wrong?

TypeError: Cannot call method "toUpperCase" of undefined. (line 132, file "Signer", project "OAuth1")

when running the following line:

var response = service.fetch(url, { headers : { "Accept" : "application/json" } });

Removing the headers parameter runs fine, but returns the wrong datatype for my needs.

how to change signature method?

In Signer.gs I see a reference to signature_method (line 48), how do I set this value (in my case to: PLAINTEXT) when using the library?

Unable to authenticate with user credentials in Twitter API

UPDATE: Disregard this comment. I was making a mistake. It works fine.

Everything works fine if I authenticate with app credentials, but I seem not to be able to authenticate with the user credentials. It throws this error all the time:

~~ {"errors":[{"code":32,"message":"Could not authenticate you."}]} (line 439, file "Service", project "OAuth1")~~

I've got access tokens and consumer keys in my Twitter app with read, write and direct messages access level.

Support for "2-legged" OAuth v1.0a?

I've been trying to get the code to work with an API which uses "2-legged" OAuth v1.0a - am I correct in saying that this authentication isn't supported? If it is, is there an example?
Thank you!

Support for Standalone Google Apps Script Projects

Being able to create sidebars is all well and good when your script is tied to a Document, but what about those of us who want to use Apps Script to interact with OAuth Services in standalone Apps Script projects? We can't call things like DocumentApp.getUi().showSidebar(page);.

Partner API requires null token and token secret

We are working with a partner and were just provided with a consumer and consumer secret, no additional authorization was required. Our existing connection is using OAuthBase and we generate a signature with a null token and token secret and send the request. Is it possible to save a null token with service.saveToken_ and bypass the initial authorization process since we are already authorized?

schedule twitter

Hi, I'm using this library to connect my google spreadsheet with twitter so I can schedule my tweets. I have a function that authorizes my app. Then I schedule my tweets and use a trigger to send out the tweets. However, in the function that sends them out, I somehow have to get such a oauth object without going through the whole authenticating process again. Can someone help me with this?

OAuth1a without TokenUrl

I'm trying to use an API that requires OAuth1 but doesn't use an URL. It just wants the consumerKey, consumerSecret, accessToken (same as consumerKey), and accessSecret (same as consumerSecret).

Are there any examples on how to use this library with it?

connect with twitter

I think I've not explained myself well enough in my previous post. I'll put some code down below to illustrate. First up I have the functions to authorize (function AUTHORIZE() being the one that's called initially)

function AUTHORIZE() {
var service = oAuth();
if (service.hasAccess()){
try {
var result = service.fetch(
"https://api.twitter.com/1.1/statuses/mentions_timeline.json");
authservice=service;
spreadsheet.toast("App authorized successfully! You can start entering your Tweets in sheet now and select Tweet Scheduler-> Schedule Tweets Now", "Authorized", 10);
} catch (e) {
Logger.log("Make sure you entered proper Twitter CONSUMER KEY and SECRET");
Browser.msgBox("OAuth Error!", "Make sure you entered correct Twitter CONSUMER KEY and SECRET", Browser.Buttons.OK);
}
}
else {
var authorizationUrl = service.authorize();
Browser.msgBox("authorize", "Click "+authorizationUrl+" to authorize", Browser.Buttons.OK);
}
}

function oAuth() {
var oauthConfig = OAuth1.createService('twitter');
oauthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey("MyRB2iMo4xOpFRH5R3mzdIBZX");
oauthConfig.setConsumerSecret("Iku0rtIbCdEmChe73niYOVQIy2BKN1g7HCH44ki110q5CvWhRN");
oauthConfig.setProjectKey("MTiqXM6kcMZT7DXQB8n7NiwRXe9kjsIBw");
oauthConfig.setCallbackFunction('authCallback');
oauthConfig.setPropertyStore(PropertiesService.getScriptProperties());
return oauthConfig;
}
function authCallback(request) {
var service = oAuth();
var isAuthorized = service.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this page.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this page');
}
}

next the function that schedules my tweets:
function scheduleTweets() {
scriptProperties.setProperty('isInitialized', 'true');
var start = getFirstRow() + 1;
var end = SpreadsheetApp.getActiveSheet().getLastRow();
deleteoldtriggers();
PropertiesService.getScriptProperties().deleteAllProperties();
for (i = start; i <= end; i++) {
if (i < 20) {
var to = sheet.getRange(i, 1).getValue();
var message = sheet.getRange(i, 2).getValue();
var message = message.substr(0, 140);
var imgurl = sheet.getRange(i, 3).getValue();
if (sheet.getRange(i, 4).getValue()) {
var time = sheet.getRange(i, 4).getValue();
var time = new Date(time);
Logger.log(to + ":" + message + time);
var time = formatTime(time);
if (time) {
savetodb(to, message, imgurl, time);
ScriptApp.newTrigger("checkschedule").timeBased().at(new Date(time)).create();

            } else {
                Logger.log("Empty/Invalid Entry");
            }
        }
    }
}
spreadsheet.toast("All your Tweets have been scheduled and will automatically be posted on your Profile at appropriate time", "Success: Tweets Scheduled", 5);

}

The checkschedule function will gather the data and finally call out the function sendouttweets:
function sendouttweets(to, tweet, imgurl) {
Logger.log("send tweet" + to + tweet + "called");
var user = to;
var tweet = tweet;
var scriptProperties = PropertiesService.getScriptProperties();
var service = "get the auth";

var options = {
    "method": "POST",
    "oAuthServiceName": "twitter",
    "oAuthUseToken": "always"
};

var status = "https://api.twitter.com/1.1/statuses/update.json";

var imgurlenc = encodeURIComponent(imgurl);

var imageurl = UrlFetchApp.fetch(imgurl);
//var imgdata = imageurl.getContent();
var imgdatablob = imageurl.getBlob().setContentTypeFromExtension();
var boundary = Math.random().toString().substr(2);

var requestBody = Utilities.newBlob(
"--"+boundary+"\r\n"
+ "Content-Disposition: form-data; name="status"\r\n\r\n"
+ status+"\r\n"+"--"+boundary+"\r\n"
+ "Content-Disposition: form-data; name="media[]"; filename=""+imgdatablob.getName()+""\r\n"
+ "Content-Type: " + imgdatablob.getContentType()+"\r\n\r\n").getBytes();

requestBody = requestBody.concat(imgdatablob.getBytes());
requestBody = requestBody.concat(Utilities.newBlob("\r\n--"+boundary+"--\r\n").getBytes());

var optionsimg = {
method: "post",
contentType: "multipart/form-data; boundary="+boundary,
oAuthServiceName: "twitter",
oAuthUseToken: "always",
payload: requestBody
};

var uploadimgres = service.fetch("https://upload.twitter.com/1.1/media/upload.json", optionsimg);
var o = JSON.parse(uploadimgres.getContentText());
try {
var imgid = o[0].media_id;

     if (user){
        status = status + "?status=" + encodeString("@" + user + " " + tweet);}
     else{
        status = status + "?status=" + encodeString(tweet);
     }
     status = status+"&media_ids="+ encodeString(imgid);
     try {
        var result = service.fetch(status, options);
     } catch (e) {
        Logger.log(e.toString());
     }
  }
  catch(e){
     Logger.log(e.toString());
  } 

}

It's in this last function that I have to somehow use a oauth object. Do I need to do the oAuth() function again? And if so, doesn't that trigger that callback again?

XeroPrivate.gs needs PLAINTEXT oauth signature method but RSA-SHA1 encoded consumer secret

I have little experience with the oauth process and I may be wrong in understanding where the issue is here. There is also a possibility this may be two different issues.

I tried running the XeroPrivate.gs script, but I get the following error from the Stackdriver log:

Invalid argument: key at unknown function at unknown function at unknown function at unknown function at unknown function at run(Code:21)

I am running version 16 of the library.

A month ago, I was running this script successfully on AppScript, but now it is no longer working since the script uses UiApp and has been deprecated. But I did notice that this script's payload is as follows:

   var payload =
  {
    "oauth_consumer_key": Xero.getProperty('consumerKey'),
    "oauth_token": e.parameter.oauth_token,
    "oauth_signature_method": "PLAINTEXT",
    "oauth_signature": encodeURIComponent(Xero.getProperty('consumerSecret') + '&' + Xero.getProperty('requestTokenSecret')),
    "oauth_timestamp": ((new Date().getTime()) / 1000).toFixed(0),
    "oauth_nonce": generateRandomString(Math.floor(Math.round(25))),
    "oauth_version": "1.0",
    "oauth_verifier": e.parameter.oauth_verifier
  };
  var options = { "method": "post", "payload": payload, muteHttpExceptions: true };

Code Source: https://github.com/rakesh456/xero-api-apps-script/blob/0440cfb0efe80c1b9f28b4bc2e2ac4386592651f/Code.gs#L27

It seems the oauth_signature_method is PLAINTEXT but in the oauth_signature, it encodes the consumerSecret in RSA-SHA1.

Any help is very much appreciated!

oauth_callback missing

Hi,
I've fetched the latest version from here and when I try to connect to Xing api (https://dev.xing.com)

with oAuth 1.0 , I get the error below

Error starting OAuth flow: {"message":"Required parameter oauth_callback missing","error_name":"REQUIRED_PARAMETER_MISSING"} (line 330, file "Service", project "OAuth1")

I haven't modified the code just changed from 1.0a to 1.0 Oauth protocol ( .setOAuthVersion('1.0') )

Method ScriptApp.getProjectKey is deprecated

I get the following warning repeatedly (I am using v12)

Method ScriptApp.getProjectKey is deprecated.Expand
File: Service Line: 32

As this method is deprecated, could you replace this with an alternate method

Implement fetchAll

I'm using this library in a situation where I have to make multiple calls to an API. I would typically use UrlFetchApp.fetchAll in such situations, but since I need to use this library's fetch method, I have to resort to making calls in series which will drastically increase execution time and eventually exceed the run-time limits.
A fetchAll method for this library would be essential for such situation.

Using multiple instances from Google Sheets

Hi,

Please do bear with me, my knowledge of Javascript is virtually non-existent.

I also understand this may not be an issue, but more of a support request (providing what I want to achieve is easy enough with the current codebase).

I'm trying something like the following in order to be able to see multiple follower accounts across my various Tumblr blogs on my sheet. Is there a different (easier?) way of doing this? Is this something that can be made easier in the future? Am I having a "senior moment"?

Everything goes as planned, until it hits the callback and then complains about the CONSUMER_KEY not being set.

Any help is appreciated. Thanks.

function getTumblrFollowerCount(id) {
  var setupCredentials = function() {
    if(id == 'notarealaccount.tumblr.com') {
      CONSUMER_KEY = '...';
      CONSUMER_SECRET = '...';
    }
  }
  setupCredentials();
  return getActualTumblrFollowerCount(id);
}

function getActualTumblrFollowerCount(id) {
  var service = getTumblrService();
  if (service.hasAccess()) {
    var response = service.fetch('https://api.tumblr.com/v2/blog/' + id + '/followers');
    var followers = JSON.parse(response);
    return parseFloat(followers.response.total_users); 
  } else {
    var authorizationUrl = service.authorize();
    return authorizationUrl;
  }
}

function tumblrReset() {
  var service = getTumblrService();
  service.reset();
}

function getTumblrService() {
  return OAuth1.createService('tumblr')
      .setAccessTokenUrl('http://www.tumblr.com/oauth/access_token')
      .setRequestTokenUrl('http://www.tumblr.com/oauth/request_token')
      .setAuthorizationUrl('http://www.tumblr.com/oauth/authorize')
      .setConsumerKey(CONSUMER_KEY)
      .setConsumerSecret(CONSUMER_SECRET)
      .setCallbackFunction('tumblrAuthCallback')
      .setPropertyStore(PropertiesService.getUserProperties());
}

function tumblrAuthCallback(request) {
  var service = getTumblrService();
  var authorized = service.handleCallback(request);
  if (authorized) {
    return HtmlService.createHtmlOutput('Success!');
  } else {
    return HtmlService.createHtmlOutput('Denied');
  }
}

Callback url length exceeds its maximum size?

Trying to use for Fitbit OAuth1.0 because my script stopped working presumably because Google is suspending OAuth1.0 support.

Error starting OAuth flow:
HTTP Status 400 - Callback url length (399) exceeds its maximum size 255
(line 299, file "Service", project "OAuth1")

Tried to follow the steps in the readme but I am not sure if I did them correctly. When I authorized originally it didn't seem to ask for the google callback url mentioned in the readme.

function getFitbitService() {
  return OAuth1.createService(identifier)
  // Set the endpoint URLs.
  .setAccessTokenUrl("https://api.fitbit.com/oauth/access_token")
  .setRequestTokenUrl("https://api.fitbit.com/oauth/request_token")
  .setAuthorizationUrl("https://api.fitbit.com/oauth/authorize")

  // Set the consumer key and secret.
  .setConsumerKey(getConsumerKey())
  .setConsumerSecret(getConsumerSecret())

  // Set the project key of the script using this library.
  .setProjectKey(projectKey)


  // 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());
 }
 function showSidebar() {
  var fitbitService = getFitbitService();

   if (!fitbitService.hasAccess()) {
       var authorizationUrl = fitbitService.authorize();
       Logger.log(authorizationUrl);
       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 fitbitService = getFitbitService();
     var isAuthorized = fitbitService.handleCallback(request);
     if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
     } else {
       return HtmlService.createHtmlOutput('Denied. You can close this tab');
     }
   }

   function authorizeForReal() {
      var options =
       {
           "oAuthServiceName": identifier,
           "oAuthUseToken": "always",
       };

     var fitbitService = getFitbitService();
     var response = fitbitService.fetch("https://api.fitbit.com/1/user/-/profile.json",options);
     var o = Utilities.jsonParse(result.getContentText());
     return o.user;
   }

Small typo in README.MD

Under header 'Callback URL'

Before you can start authenticating against an OAuth2 provider,
should be
Before you can start authenticating against an OAuth1 provider,

The library does not work with Tradevine api

I am trying to use the library with tradevine api(api.tradevine.com). I have configured it properly, but I get this error:
"Error starting OAuth flow: Object reference not set to an instance of an object. (line 313, file "")"

On further investigation, I see that this line(in Service.gs):
throw 'Error starting OAuth flow: ' + response.getContentText();

is givine the error.
I am stuck to make this work and I don't find any alternatives.

The tradevine also provides a token and a secret apart from the consumer key and secret.
So we can skip this step of getting the token.
How do I use this library with token and secret?

issues with sending requests with ampersands in POST body

UrlFetchApp.fetch() works incorrectly when the payload is an object and one or more of the parameter values contains an ampersand (&). This creates issues with sending OAuthed statuses with ampersands to Twitter, for example. You will get "Could not authenticate you" errors because the post body sent by UrlFetchApp does not correspond to the one used to created the signature.

I recommend manually stringifying the payload to a correct POST body before sending the data if the content is going to be urlencoded (this is what I was doing under the old OAuth service, and worked well). However, if there is a blob in the payload, it will be sent multipart/form-data instead, so check for that:

//Service.gs, line 398
// Service_.prototype.fetchInternal_()
if(params.payload && !Object.keys(params.payload).reduce(function(truth, key) {
  return truth || typeof params.payload[key] === "object";
}, false)) {
  params.payload = signer.getParameterString(request, {});
}
return UrlFetchApp.fetch(url, params);

Getting: "The state token is invalid or has expired. Please try again." - no call of authCallback

I am setting the callback function like in README.md

var service = OAuth1.createService('meh');
...
service.setCallbackFunction('authCallback');

I am jumping to "usercallback" Url where I am getting "The state token is invalid or has expired. Please try again.".

I am expecting that authCallback function will be called but its not the case.

Script is running under Googel for Works

https://script.google.com/a/macros/fancy-domain.org/d/ProjectId/usercallback?state=ADEpC8ytq-GO0eq0qvx-Uvv3IEPOBqwCN9DuPpyll_y0fPRnxgkx-kJwoszp8mvsiN_16JlL27bWc1I22xoielBWXqRNK0yywlsTtOzyAEIJHMlfA3sZpftblybm8Craztn3LSMxuybH9Sq68qCxouyb8PAojn5OnM2ygJf&oauth_token=b4f5a69611fb5c9083e9a3040089e92e&oauth_verifier=d30ea54d161ce0d8ed49ee52e6736225

Lack of RSA-SHA1 support

HI guys!

Have a trouble with authenticating w/ JIRA REST API, because they support only RSA-SHA1(not SHA2).
Will there be support in the future of RSA-SHA1 ?

<wbr> tags resulting in 401 errors

I am programming in Google Script. Since migrating towards oath1 (I use the shared libray posted on github, thanks for that!!!) I seem to get errors caused by '' tags in the urls.

I tried switching of 'escaping' (via the parameters). As far as I can see the '' tag is added after I do the fetch via the auth1 service clas...

The actual code is like this:

var requestData = {
"method": "POST",
"escaping":false
};

var result = service.fetch(url,requestData);

The error I get (with Dutch keywords, I hope this is not a problem, i replaced the wbr tag by WBRTAG otherwise it is replaced by a return when viewing):

20:39doSomeTriggeredThingsVerzoek voor https://api.twitter.com/1.1/WBRTAGstatuses/update.json?status=WBRTAGNieuw%20bij%20BoekenRoute%3A%WBRTAG20%22De%20avonturen%20van%WBRTAG20Alice%20in%20Wonderland%20%WBRTAG26%20Spiegelland%22%2C%WBRTAG20Lewis%20Carroll%2C%20%WBRTAG20Uitgeverij%20...%22

Foutcode: 401. Ingekorte serverreactie: {"errors":[{"code":32,"message":"Could not authenticate you."}]} (Gebruik de optie muteHttpExceptions om de volledige reactie te onderzoeken.) (regel 423, bestand 'Service', project 'OAuth1'

Anyone any ideas? It happens not 'all the time'... maybe say 1 out of 10 calls?

THANK YOU!
Iwanjka (Netherlands / Malawi)

Security: OAuth Client ID and Secret are accessible to any user of an Apps Script in almost all samples

This mirrors the same issue in the OAuth2 library: googleworkspace/apps-script-oauth2#378

getService() or the equivalent method is public in almost all of the available samples and documentation, instead of having a trailing underscore like getService_().

This means that any user can call getService by using google.script.run in the browser console, which will return the application's OAuth Client ID and Secret (which are not supposed to be given to users!). This allows any user of an extension to impersonate that extension by using its ID/Secret.

This issue was discovered during an internal security review for an extension I was building, and unfortunately it means that anyone who has copied one of the samples here and is using it in production is currently vulnerable to having their Client ID/Secret read by any user of the extension, provided they did not change the getService method to be private.

I reported this issue through https://g.co/vulnz per the security policy https://github.com/googleworkspace/apps-script-oauth2/security/policy and was told to open a public issue on this repo (issue tracker reference: https://issuetracker.google.com/issues/238056715)

I have a PR ready to go that fixes this issue for the samples right now, but unfortunately it won't retroactively fix it for anyone who has copied a sample.

Tumblr callback gets undefined consumer key

Setting a hardcoded string as a the consumerKey and consumerSecret works fine, but getting it dynamically from a Sheet cell causes the callback to fail. Consumer Key is required. (line 43, file "Utilities", project "OAuth1") is displayed as the error message on the callback.

To reiterate in code:
This fails:

return OAuth1.createService('tumblr')
      // Set the endpoint URLs.
      .setAccessTokenUrl('http://www.tumblr.com/oauth/access_token')
      .setRequestTokenUrl('http://www.tumblr.com/oauth/request_token')
      .setAuthorizationUrl('http://www.tumblr.com/oauth/authorize')

      // Set the consumer key and secret.
      .setConsumerKey(getActiveSheetTumblrKey())
      .setConsumerSecret(getActiveSheetTumblrSecret())

      // Set the name of the callback function in the script referenced
      // above that should be invoked to complete the OAuth flow.
      .setCallbackFunction('tumblrAuthCallback')

      // Set the property store where authorized tokens should be persisted.
      .setPropertyStore(PropertiesService.getUserProperties());

But this works:

return OAuth1.createService('tumblr')
      // Set the endpoint URLs.
      .setAccessTokenUrl('http://www.tumblr.com/oauth/access_token')
      .setRequestTokenUrl('http://www.tumblr.com/oauth/request_token')
      .setAuthorizationUrl('http://www.tumblr.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('tumblrAuthCallback')

      // Set the property store where authorized tokens should be persisted.
      .setPropertyStore(PropertiesService.getUserProperties());

Ampersands breaking encoding

Hi,

I'm using this in the context of a twitter bot, and I've found what I think is a bug. (I could be wrong, though.) What's happening is that when the payload (status=urlencodedtweet) includes and ampersand, the library treats that ampersand as the beginning of a new tweet.

I'm not sure, but I think this happens here, where the deParam function on the Signer decodes it first and then splits it on '&'. Seems to me that it should split it on '&' before decoding it, but I haven't been able to test this theory.

For now, at least, the buggy behavior seems to be consistent: that using an ampersand in a tweet causes part of the payload to get dropped.

Any suggestions?

Thanks,
Zach

Library not able to connect to Xero

While trying to establish an OAuth 1.0a based connection to Xero I am stuck. Would really appreciate if you could look into the issue.

Here is how my getService() function looks like:

  var service = OAuth1.createService('xero');
  service.setAccessTokenUrl('https:­//a­pi.x­er­o.c­om/­oau­th/­Acc­ess­Token');
  service.setRequestTokenUrl('https://api.xero.com/oauth/RequestToken');
  service.setAuthorizationUrl('https://api.xero.com/oauth/Authorize');
  service.setConsumerKey(CONSUMER_KEY);
  service.setConsumerSecret(CONSUMER_SECRET);
  service.setProjectKey(PROJECT_KEY);
  service.setCallbackFunction('authCallback');
  service.setPropertyStore(PropertiesService.getScriptProperties());

I get an error when I do a service.hasaccess()

The error shown is:
Error starting OAuth flow: oauth_problem=xero_unknown_error&oauth_problem_advice=could%20not%20generate%20a%20request%20token (line 330, file "Service", project "OAuth1")

Any help would be highly appreciated

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.