Google Apps スクリプトに aws cognito 認証を含めるにはどうすればよいですか?

okwaves2024-01-25  10

Google シートの App Script から、aws-cognito-identity による認証を使用してデータベースにアクセスしようとしています。 Node.js環境ではないため、モジュールのインポート方法がわからず、始めることすらできず困っています。誰かこれをやった経験があり、それを共有しても構わないでしょうか? ありがとう

検索

– ザマスター

2020 年 9 月 3 日 15:04



------------------------

これが私がこれを機能させる方法です:

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()
    },
共有 この回答を改善します フォローする

2021 年 5 月 3 日 18:14 に回答

ATM の流れ

ATM の流れ

1

総合生活情報サイト - OKWAVES
総合生活情報サイト - OKWAVES
生活総合情報サイトokwaves(オールアバウト)。その道のプロ(専門家)が、日常生活をより豊かに快適にするノウハウから業界の最新動向、読み物コラムまで、多彩なコンテンツを発信。