【问题标题】:Trouble authorizing using OAuth with StackExchange API and Apps Script使用带有 StackExchange API 和 Apps 脚本的 OAuth 进行授权时遇到问题
【发布时间】:2019-01-15 10:56:42
【问题描述】:

我正在尝试使用 Google Apps 脚本中的 OAuth 访问 StackExchange API。我正在使用this library

当我拨打以下电话时,我一开始没有访问权限(这是预期的)。我登录的授权网址是:

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

将 autorizationURL 粘贴到我的浏览器中,我得到如下页面:

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

我从 Apps 脚本运行的内容:

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);
   }
 }

我的 Oauth.gs 页面:

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');
  }
}

不清楚我哪里出错了,但我认为当我输入授权 URL 时我应该被重定向到授权页面。谢谢!

【问题讨论】:

  • 试试setTokenUrl('https://stackoverflow.com/oauth/access_token/json')
  • 成功了!非常感谢@TheMaster

标签: google-apps-script oauth oauth-2.0 stackexchange-api


【解决方案1】:

问题:

Stackexchange API,默认发送访问令牌为application/x-www-form-urlencoded,OAuth2库的tokenFormat默认需要JSON。

解决方案:

  • 通过将 tokenUrl 设置为 https://stackoverflow.com/oauth/access_token/json

    ,显式请求 JSON 的 api
  • 在OAuth2库中显式设置tokenFormat以形成使用setTokenFormat(TOKEN_FORMAT.FORM_URL_ENCODED)编码的url

参考资料:

【讨论】:

    猜你喜欢
    • 2018-12-29
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多