poyter16
poyter16

Reputation: 25

Trouble authorizing using OAuth with StackExchange API and Apps Script

I'm trying to access StackExchange API, using OAuth in Google Apps Script. I'm using this library.

When I call the below, I don't have access at first (which is expected). The authorization URL I log is:

https://stackoverflow.com/oauth?client_id=14205&response_type=code&redirect_uri={URI}&state={STATE}&scope=read_inbox 

Pasting the autorizationURL into my browser, I get the page that reads:

"Error: Token response not valid JSON: SyntaxError: Unexpected token: a (line 532, file "Service", project "OAuth2")"

What I run from Apps Script:

function getMentions() {
   var service = getStackExchangeService_();
   Logger.log(service.hasAccess());
   if (service.hasAccess()) {

     //get token and call API
   }
   else {
   Logger.log("App has no access yet.");

   // open this url to gain authorization from Stack Exchange
   var authorizationUrl = service.getAuthorizationUrl();

   Logger.log("Open the following URL and re-run the script: %s",
     authorizationUrl);
   }
 }

My Oauth.gs page:

function getStackExchangeService_() {
  var CLIENT_ID = PropertiesService.getScriptProperties().getProperty('SE_CLIENT_ID');
  var CLIENT_SECRET = PropertiesService.getScriptProperties().getProperty('SE_CLIENT_SECRET');

  return OAuth2.createService('StackExchange')
  .setAuthorizationBaseUrl('https://stackoverflow.com/oauth')
  .setTokenUrl('https://stackoverflow.com/oauth/access_token')
  .setClientId(CLIENT_ID)
  .setClientSecret(CLIENT_SECRET)
  .setCallbackFunction('authCallbackSE')
  .setPropertyStore(PropertiesService.getUserProperties())
  .setRedirectUri('https://script.google.com/macros/d/{SCRIPT ID}/usercallback')
  .setScope('read_inbox');
}

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

Unclear where I am going wrong, but I assume that I should be redirected to an authorization page when I put in the authorizationURL. Thanks!

Upvotes: 2

Views: 310

Answers (1)

TheMaster
TheMaster

Reputation: 50383

Issue:

Stackexchange API, by default sends access token as application/x-www-form-urlencoded and tokenFormat of OAuth2 library expects JSON by default.

Solutions:

  • Explicitly request the api for JSON by setting tokenUrl to https://stackoverflow.com/oauth/access_token/json OR

  • Explicitly set tokenFormat in the OAuth2 library to form url encoded using setTokenFormat(TOKEN_FORMAT.FORM_URL_ENCODED)

References:

Upvotes: 2

Related Questions