这是一个略微不同的方法,因为它只使用一个秘密,但我认为它可能有助于其他遇到这个问题的人。我通过为Cognito触发器创建自定义lambda(Define Auth Challenge、Create Auth Challenge和Verify Auth Challenge)来实现这一点。
我的需求是,我希望我的后端使用一个“秘密”来获取任何Cognito用户的访问和刷新令牌。
“Define Auth Challenge Lambda”
exports.handler = async event => {
if (
event.request.session &&
event.request.session.length >= 3 &&
event.request.session.slice(-1)[0].challengeResult === false
) {
event.response.issueTokens = false;
event.response.failAuthentication = true;
} else if (
event.request.session &&
event.request.session.length &&
event.request.session.slice(-1)[0].challengeResult === true
) {
event.response.issueTokens = true;
event.response.failAuthentication = false;
} else {
event.response.issueTokens = false;
event.response.failAuthentication = false;
event.response.challengeName = 'CUSTOM_CHALLENGE';
}
return event;
};
创建身份验证挑战Lambda
exports.handler = async event => {
if (event.request.challengeName == 'CUSTOM_CHALLENGE') {
event.response.publicChallengeParameters = { foo: 'bar' };
}
return event;
};
验证身份认证挑战Lambda
exports.handler = async event => {
if (event.request.challengeName == 'CUSTOM_CHALLENGE') {
event.response.publicChallengeParameters = { foo: 'bar' };
}
return event;
};
我随后使用amazon-cognito-identity-js编写了一些JS代码,提供了密钥并获取了令牌:
var authenticationData = {
Username : 'username'
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = {
UserPoolId : '...',
ClientId : '...'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username : 'username',
Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.setAuthenticationFlowType('CUSTOM_AUTH');
cognitoUser.initiateAuth(authenticationDetails, {
onSuccess: function(result) {
},
onFailure: function(err) {
},
customChallenge: function(challengeParameters) {
var challengeResponses = 'secret'
cognitoUser.sendCustomChallengeAnswer(challengeResponses, this);
}
});