如何使用带有 GAS 的 UrlFetchApp 获取访问令牌 [英] How do I get an access token using UrlFetchApp with GAS

查看:16
本文介绍了如何使用带有 GAS 的 UrlFetchApp 获取访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何将 REST 端点与 Google Apps Script (GAS) 结合使用,并希望获取示例中的访问令牌 这里

我正在使用 Google 协作平台,这是脚本

function doGet(e) {var app = UiApp.createApplication().setTitle('test OAuth 2.0');var mainPanel = app.createVerticalPanel();app.add(mainPanel);var url = "https://accounts.google.com/o/oauth2/auth" +"?scope=https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile" +"&state=/profile" +"&redirect_uri=http://<mySite>.com/gas/home/oauth2apis" +"&response_type=token" +"&client_id=812741506391.apps.googleusercontent.com" +"&approval_prompt=force";Logger.log("encodeURI(url):"+encodeURI(url));尝试{var response = UrlFetchApp.fetch(encodeURI(url));}catch(e){Logger.log("抓住了这个:" + e);}Logger.log("响应码:"+response.getResponseCode());Logger.log("X-自动登录响应码:"+response.getHeaders());var 返回 = app.createTextArea().setHeight(600).setValue(response.getContentText());mainPanel.add(返回);返回应用程序;}

和 Logger.log

响应码:200X-Auto-Login 响应代码:({'Cache-control':"no-cache, no-store", Expires:"Mon, 01-Jan-1990 00:00:00 GMT", 'X-XSS-Protection':"1; mode=block", 'Set-Cookie':"GALX=m0d9oxyH-kQ;Path=/;Secure", 'X-Google-Cache-Control':"remote-fetch", Server:"GSE", Pragma:"no-cache", 'X-Content-Type-Options':"nosniff", 'X-Frame-Options':"拒绝", 'X-Auto-Login':"realm=com.google&args=service%3Dlso%26continue%3Dhttps%253A%252F%252Faccounts.google.com%252Fo%252Foauth2%252Fauth%253Fresponse_type%253Dtoken%2526scope%253Dhttps%252Fo%2Fo%252Bhttps%253A%252F%252Fwww.googleapis.com%252Fauth%252Fuserinfo.profile%2526redirect_uri%253Dhttp%253A%252F%252F< MYSITE> .COM%252Fgas%252Fhome%252Foauth2apis%2526approval_prompt%253Dforce%2526state%253D%252Fprofile%2526client_id%253D812741506391.apps.googleusercontent.com%2526hl%253Den-US%2526from_login%253D1%2526as%253D6991e98fb6d20df3", 'Sport-age000="10000df3", 'S2000000df3", 'Sport-age000'Sn 2012 12:46:26 GMT", Via:"HTTP/1.1 GWA", 'Content-Type':"text/html;字符集=UTF-8"})

mySite 已映射并在 dns 中.

看起来它正在尝试进行重定向(我对 OAuth 的理解有限,这对我来说很有意义)但返回码是 200,重定向是 302?

我可以使用 urlFetchApp 获取访问令牌吗?

解决方案

您尝试检索的 URL 不应由您的应用程序检索 - 您需要将最终用户重定向到该 URL.然后最终用户授予您的应用访问其数据的能力,然后 Google 会将用户重定向回您的应用.

由于我不相信 Google 提供了从 Google Apps 脚本运行客户端 JavaScript 的能力,因此您将需要使用网络服务器(授权代码)流程.这意味着当用户重定向回您的应用程序时,该 URL 将包含授权代码.然后,您从 Apps 脚本向 OAuth 2.0 令牌端点发出服务器到服务器请求,以交换 OAuth 访问令牌的授权代码.

这是一些示例代码(没有正确的错误处理等.但它可以运行):

function doGet(e) {var scriptUri = "https://docs.google.com/macros/s/AKfycbzg1LZIqKlKu5f7TtRL4VuleEjExXVCEqH15fI3/exec";var clientId = "764634415739.apps.googleusercontent.com";var clientSecret = "XXXXXXX-YYYYYYYYY";var scope = "https://www.googleapis.com/auth/plus.me";var app = UiApp.createApplication().setTitle("");var div = app.createVerticalPanel();if (e.parameter && e.parameter.code) {var redirectUri = scriptUri;var tokenEndpoint = "https://accounts.google.com/o/oauth2/token";var postPayload = {代码":e.parameter.code,client_id":clientId,client_secret":clientSecret,redirect_uri":redirectUri,grant_type":授权代码"};变量选项 = {方法":发布",有效载荷":postPayload};//获取 URL 以将授权码发布到谷歌//并取回访问令牌var response = UrlFetchApp.fetch(tokenEndpoint, options);var tokenData = Utilities.jsonParse(response.getContentText());//调用 Google+ API 并获得响应var plusOptions = {标题":{授权":承载"+ tokenData.access_token}};var plusResponse = UrlFetchApp.fetch("https://www.googleapis.com/plus/v1/people/me", plusOptions);var plusData = Utilities.jsonParse(plusResponse.getContentText());div.add(app.createLabel(plusData.displayName));div.add(app.createLabel(plusData.url));} 别的 {//要求用户转到 Google 授予访问权限var redirectUri = scriptUri;var url1 = "https://accounts.google.com/o/oauth2/auth?client_id=" + clientId +"%26response_type=code" +"%26scope=" + 范围 +"%26redirect_uri="+redirectUri;div.add(app.createAnchor('Grant data access at Google',url1));}app.add(div);返回应用程序;}

这是正在运行的代码:https://docs.google.com/macros/s/AKfycbzg1LZIqKlKu5f7TtRL4VuleEjExXVCEqH15fI3/exec">https://docs.google.com/macros/s/AKfycbzg1LZIqKlKu5f7TjexecHlKu5f7TtRL4VuleEjExXVCEqH15fI3/exec>CEVe

I am learning how to use the REST endpoints with Google Apps Script (GAS) and want to get the access token like the example here

I'm using Google Sites, here is the script

function doGet(e) {
  var app = UiApp.createApplication().setTitle('test OAuth 2.0');

  var mainPanel = app.createVerticalPanel();
  app.add(mainPanel);

  var url = "https://accounts.google.com/o/oauth2/auth" + 
                     "?scope=https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile" +
                     "&state=/profile" +
                     "&redirect_uri=http://<mySite>.com/gas/home/oauth2apis" +
                     "&response_type=token" +
                     "&client_id=812741506391.apps.googleusercontent.com" +
                     "&approval_prompt=force";
  Logger.log("encodeURI(url):"+encodeURI(url));

  try{
    var response = UrlFetchApp.fetch(encodeURI(url));
  }catch(e){
    Logger.log("caught this:" + e);
  }

  Logger.log("Response code:"+response.getResponseCode());
  Logger.log("X-Auto-Login Response code:"+response.getHeaders());

  var returned = app.createTextArea().setHeight(600).setValue(response.getContentText());
  mainPanel.add(returned);
  return app;
}

and the Logger.log

Response code:200
X-Auto-Login Response code:({'Cache-control':"no-cache, no-store", Expires:"Mon, 01-Jan-1990 00:00:00 GMT", 'X-XSS-Protection':"1; mode=block", 'Set-Cookie':"GALX=m0d9oxyH-kQ;Path=/;Secure", 'X-Google-Cache-Control':"remote-fetch", Server:"GSE", Pragma:"no-cache", 'X-Content-Type-Options':"nosniff", 'X-Frame-Options':"Deny", 'X-Auto-Login':"realm=com.google&args=service%3Dlso%26continue%3Dhttps%253A%252F%252Faccounts.google.com%252Fo%252Foauth2%252Fauth%253Fresponse_type%253Dtoken%2526scope%253Dhttps%253A%252F%252Fwww.googleapis.com%252Fauth%252Fuserinfo.email%252Bhttps%253A%252F%252Fwww.googleapis.com%252Fauth%252Fuserinfo.profile%2526redirect_uri%253Dhttp%253A%252F%252F<mySite>.com%252Fgas%252Fhome%252Foauth2apis%2526approval_prompt%253Dforce%2526state%253D%252Fprofile%2526client_id%253D812741506391.apps.googleusercontent.com%2526hl%253Den-US%2526from_login%253D1%2526as%253D6991e98fb6d20df3", 'Strict-Transport-Security':"max-age=2592000; includeSubDomains", Date:"Sat, 16 Jun 2012 12:46:26 GMT", Via:"HTTP/1.1 GWA", 'Content-Type':"text/html; charset=UTF-8"})

mySite is mapped and in dns.

It looks like it is trying to do a redirect (which makes sense to me with my limited understanding of OAuth) but the return code is a 200 and a redirect is a 302?

Can I use urlFetchApp to get the access token?

解决方案

The URL you're trying to retrieve shouldn't be retrieved by your app-- you need to redirect the end-user to the URL. The end-user then grants the ability for your app to access their data, and then Google will redirect the user back to your app.

Since I don't believe Google provides the ability to run client-side JavaScript from Google Apps Script, you're going to want to use the web server (authorization code) flow. This means that the URL will contain an authorization code when the user is redirected back to your app. You then do a server-to-server request from Apps Script to the OAuth 2.0 token endpoint to exchange the authorization code for an OAuth access token.

Here's some example code (without proper error handling, etc.. but it runs):

function doGet(e) {
  var scriptUri = "https://docs.google.com/macros/s/AKfycbzg1LZIqKlKu5f7TtRL4VuleEjExXVCEqH15fI3/exec";
  var clientId = "764634415739.apps.googleusercontent.com";
  var clientSecret = "XXXXXXX-YYYYYYYYY";
  var scope = "https://www.googleapis.com/auth/plus.me";


  var app = UiApp.createApplication().setTitle("");
  var div = app.createVerticalPanel();

  if (e.parameter && e.parameter.code) {
    var redirectUri = scriptUri;
    var tokenEndpoint = "https://accounts.google.com/o/oauth2/token";

    var postPayload = {
      "code" : e.parameter.code,
      "client_id" : clientId,
      "client_secret" : clientSecret,
      "redirect_uri" : redirectUri,
      "grant_type" : "authorization_code"
    };

     var options = {
      "method" : "post",
      "payload" : postPayload
    };

    // do a URL fetch to POST the authorization code to google
    // and get an access token back
    var response = UrlFetchApp.fetch(tokenEndpoint, options);
    var tokenData  = Utilities.jsonParse(response.getContentText());

    // call the Google+ API and get response
    var plusOptions = {
      "headers" : {
        "Authorization" : "Bearer " + tokenData.access_token
      }
    };
    var plusResponse = UrlFetchApp.fetch(
      "https://www.googleapis.com/plus/v1/people/me", plusOptions);
    var plusData = Utilities.jsonParse(plusResponse.getContentText());

    div.add(app.createLabel(plusData.displayName));
    div.add(app.createLabel(plusData.url));

  } else {
    // ask user to go over to Google to grant access
    var redirectUri = scriptUri;
    var url1 = "https://accounts.google.com/o/oauth2/auth?client_id=" + clientId + 
        "%26response_type=code" +
        "%26scope=" + scope +
        "%26redirect_uri=" + redirectUri; 
    div.add(app.createAnchor('Grant data access at Google',url1));   
  }
  app.add(div);


  return app;
}

Here's the code in action: https://docs.google.com/macros/s/AKfycbzg1LZIqKlKu5f7TtRL4VuleEjExXVCEqH15fI3/exec

这篇关于如何使用带有 GAS 的 UrlFetchApp 获取访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆