google-apps-script - 如何在谷歌应用程序脚本中包含 aws cognito 身份验证?
问题描述
从 Google Sheet 的 App Script 中,我们尝试通过 aws-cognito-identity 使用身份验证访问我们的数据库。我什至无法入门,因为我不确定如何导入模块,因为这不是 node.js 环境。有没有人有这样做的经验并且不介意分享它?谢谢
解决方案
这就是我让它工作的方式:
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()
},
推荐阅读
- azure - Azure 隔离计时器触发功能在部署到 Azure 后不起作用
- reactjs - 卡在 Edit src/App.js 并保存以在 heroku 重新加载
- ios - 当我们尝试删除服务器时,如何停止音频会话“outputVolume”观察者崩溃
- python - 尝试打印包含 int 和 str 的列表,但不打印整数
- google-apps-script - 为什么 Google 表格网络应用需要验证会导致“查看、编辑、创建和删除您的所有 Google 表格电子表格”
- jenkins - 从管道脚本解析 Jenkins 轮询日志
- apache-spark - 如何在窗口 10 (HADOOP_HOME) 的单个环境变量中设置两个路径
- android - Android studio 需要为 Mac Monterey 更新
- ios - 如何使用 PickerView 值作为 Timer 倒计时的起始编号
- javascript - 正则表达式忽略文本中间的破折号或连字符