感谢这个问题(来自一位 Python 开发人员,对最近的节点模式有一些追赶)。基于这个 SO 和其他一些 OSS 源,以下似乎工作,给定一个合适的配置文件(见下文)。这是一个 nodejs 模块(解决方案在浏览器中会略有不同)。
/* jshint esversion: 8 */
/* jshint node: true */
// The amazon-cognito-identity-js package assumes fetch is available in a web browser. Since
// nodejs does not have fetch built-in it is emulated like this:
global.fetch = require("node-fetch");
const AmazonCognitoIdentity = require("amazon-cognito-identity-js");
function asyncCognitoAuthentication(cognitoConfig) {
const cognitoUserPool = new AmazonCognitoIdentity.CognitoUserPool({
UserPoolId: cognitoConfig.userPoolId,
ClientId: cognitoConfig.clientId,
});
const cognitoUser = new AmazonCognitoIdentity.CognitoUser({
Username: cognitoConfig.username,
Pool: cognitoUserPool,
});
const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
{
Username: cognitoConfig.username,
Password: cognitoConfig.password,
}
);
return new Promise(function (resolve, reject) {
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: resolve,
onFailure: reject,
newPasswordRequired: resolve,
});
});
}
const cognitoJWT = {
session: undefined,
jwtAccess: undefined,
jwtId: undefined,
jwtRefresh: undefined,
jwtPayloads: undefined,
};
module.exports.getCognitoJWT = async function (cognitoConfig) {
try {
const session = await asyncCognitoAuthentication(cognitoConfig);
cognitoJWT.session = session;
cognitoJWT.jwtAccess = session.getAccessToken().getJwtToken();
cognitoJWT.jwtId = session.getIdToken().getJwtToken();
cognitoJWT.jwtRefresh = session.getRefreshToken().getToken();
cognitoJWT.jwtPayloads = {
jwtAccess: session.getAccessToken().decodePayload(),
jwtId: session.getIdToken().decodePayload(),
};
return cognitoJWT;
} catch (error) {
console.log(error.message);
}
};
const process = require("process");
if (process.env.TEST_AUTH === "test") {
const config = require("config");
const cognitoConfig = config.get("cognito");
console.log(cognitoConfig);
Promise.resolve(module.exports.getCognitoJWT(cognitoConfig)).then(
(cognitoJWT) => {
console.log(cognitoJWT);
}
);
}
该config
文件位于 中./config/default.json
,其结构如下(将实际值替换为{}
字段):
{
"logLevel": "info",
"cognito": {
"clientId": "{client-app-id}",
"userPoolId": "{aws-coginto-pool-id}",
"region": "{aws-region}",
"username": "{your-username}",
"password": "{your-password}"
}
}
package.json
就像:
{
"scripts": {
"test-cognito-auth": "TEST_AUTH=test node ./cognito_auth.js"
},
"license": "Apache 2.0",
"dependencies": {
"amazon-cognito-identity-js": "^4.3.0",
"aws-sdk": "^2.686.0",
"config": "^3.3.1",
"node-fetch": "^2.6.0",
"process": "^0.11.10",
},
"devDependencies": {
"prettier": "^2.0.5"
}
}