【问题标题】:Question regarding Google Apps Script oAuth2 Third Party Authentification Code关于 Google Apps 脚本 oAuth2 第三方身份验证代码的问题
【发布时间】:2021-06-19 13:12:34
【问题描述】:

这是我第一次发布堆栈溢出问题,因为我遇到了无法解决的问题。

我想做什么:

我正在尝试从“Mercedes me”平台提取我的汽车数据。这是一个纯粹的爱好项目。

“Mercedes me”有一个带有 oAuth2 验证的 API。

我想在 Google 表格中实现这一点,因为我想用检索到的数据进行计算。

因此我开始使用 Apps 脚本进行编码。

我可以使用令牌交换验证码,然后使用以下代码从平台获取数据:


  var options = {
  headers : { Authorization: 'Basic '+ Utilities.base64Encode('Client ID:Client Secret')},
  method : 'post',
  'content-type' : 'application/x-www-form-urlencoded',
  muteHttpExceptions : false,
  }
  var authorization_code = 'TGVWD9pNif1wuDBYa6fFPn4QHNW9h6_f2-kxL34V'

  var authUrl = 'https://id.mercedes-benz.com/as/token.oauth2?grant_type=authorization_code&code='+authorization_code+'&redirect_uri=https://localhost/';
  var response = UrlFetchApp.fetch(authUrl, options);
  var data = JSON.parse(response);
  var token = data.access_token
  'Logger.log(token);'



var options = {
  headers : { Authorization: `Bearer ${token}`},
  accept : 'application/json'
}


    var response = UrlFetchApp.fetch('https://api.mercedes-benz.com/vehicledata/v2/vehicles/<vehicle identification number>/resources/', options);    
    'var jsonObject = JSON.parse(response.getContentText()); '
    'var jsonObject = JSON.stringify(response);'
    Logger.log(response);

所以这不是问题。问题是目前我需要手动插入授权码(如您在上面的代码 sn-p 中所见),然后我的脚本将与令牌交换。目标是自动生成授权码。

我创建了一个授权 URL,当在浏览器中输入和打开时,它会给我授权代码。 但是,当我尝试通过 UrlFetchApp 在 Apps 脚本中实现相同功能时,它会向我发送一些无法使用的 html 代码而不是授权代码。

function Authentification() {

var url = 'https://id.mercedes-benz.com/as/authorization.oauth2?response_type=code&client_id=a9f67f5f-cb2b-413b-9ea5-78df02b668a1&redirect_uri=https://localhost/&scope=mb:vehicle:mbdata:payasyoudrive&state=1000';

var options = {
  muteHttpExceptions : false, //theoretisch nicht notwendig
  followRedirects : true, //theoretisch nicht notwendig
  method : 'get', //theoretisch nicht notwendig
}

var response = UrlFetchApp.fetch(url, options);
var json = response.getHeaders;
var data = JSON.stringify(json);

Logger.log(response)


}

结果是一些像这样的html:

<!DOCTYPE html><html lang=en xmlns=http://www.w3.org/1999/xhtml><head><meta charset=utf-8><m

但我正在尝试获取这样的重定向网址(包括授权码):

https://localhost/?code=DXPzKdV58t3rWlpuVmD3XT35BbL__n0auuAxL34V&state=1000

我的假设是,问题在于,当 Apps Script 的 URLFetchApp 打开链接时,从未要求输入我的“Mercedes me”登录凭据。很可能我在这里没有看到基本的 OAuth 逻辑。非常感谢您的帮助。提前非常感谢。

最好的问候, 克里斯

【问题讨论】:

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


    【解决方案1】:

    我在睡梦中想到了解决方案:-D

    我将整个东西部署为一个 webapp,并使用 webapp-link 作为重定向 uri。

    在此之后,我能够使用以下代码从 url 中提取授权代码:

    function doGet(e) {
      var param = e.queryString;
      param = e.parameter;
      var code = param.code;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 2015-12-07
      • 2014-08-16
      • 1970-01-01
      相关资源
      最近更新 更多