首页 > 解决方案 > 如何在谷歌应用程序脚本中包含 aws cognito 身份验证?

问题描述

从 Google Sheet 的 App Script 中,我们尝试通过 aws-cognito-identity 使用身份验证访问我们的数据库。我什至无法入门,因为我不确定如何导入模块,因为这不是 node.js 环境。有没有人有这样做的经验并且不介意分享它?谢谢

标签: google-apps-scriptamazon-cognito

解决方案


这就是我让它工作的方式:

var authEndpoint = "https://[put your auth domain here].amazoncognito.com/oauth2/token";
var authClientId = "[put your Cognito client ID here]";
var authSecret = "[put your Cognito auth secret string here]";
var authExpirationTime = undefined;
var authLatestToken = undefined;

function getAuthToken() {
  // If last known token is still valid, use it.
  if (authLatestToken && authExpirationTime && authExpirationTime < new Date().getTime()) {
    return authLatestToken;
  }

  // Otherwise, request new token from AWS Cognito
  var params = {
    method: "POST",
    followRedirects: true,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Authorization": "Basic " + Utilities.base64Encode(authClientId + ":" + authSecret)
    },
    payload: "grant_type=client_credentials"
  };
  var response = UrlFetchApp.fetch(authEndpoint, params);

  // Verify response
  if (response.getResponseCode() !== 200) {
    throw new Error("Authentication failed: HTTP Response not OK.");
  }
  var data = JSON.parse(response.getContentText());
  if (!data.access_token) {
    throw new Error("Authentication failed: No token returned.");
  }

  // Set internal vars and return token
  authLatestToken = data.access_token;
  if (data.expires_in > 0) {
    authExpirationTime = new Date().getTime() + data.expires_in * 1000;
  }
  return authLatestToken;
}

然后,您可以将带有此承载的授权标头添加到任何需要进行身份验证的请求中,例如:

    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer " + getAuthToken()
    },

推荐阅读