如何解决如何在Google Apps脚本中包含AWS Cognito身份验证?
我们正在尝试通过aws-cognito-identity通过身份验证通过Google Sheet的应用脚本访问数据库。我什至没有上手的麻烦,因为我不确定如何导入模块,因为这不是一个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()
},
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。