通过 amazon-cognito-identity-js 对用户进行身份验证时,我能够对用户进行身份验证并登录。但是,访问令牌/ID 令牌与我通过 cognito 中的 AWS 托管 UI 登录用户时不同。我无法授权使用令牌的用户访问我的受保护 API,该 API 使用 cognito 作为授权方。使用两种不同的登录方法生成两个不同的 id/访问令牌是否有某种原因?
这是我登录用户的代码
const handleLogin = async (data) => {
const authenticationData = {
Username: data.get('username'),
Password: data.get('password'),
}
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(
authenticationData
)
var userData = {
Username: data.get('username'),
Pool: userPool,
}
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData)
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
console.log('result', result)
var accessToken = result.getAccessToken().getJwtToken()
//POTENTIAL: Region needs to be set if not already set previously elsewhere.
AWS.config.region = '<redacted>'
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: '<redacted>', // your identity pool id here
Logins: {
// Change the key below according to the specific region your user pool is in.
'<redacted>': result
.getIdToken()
.getJwtToken(),
},
})
AWS.config.credentials.clearCachedId()
//refreshes credentials using AWS.CognitoIdentity.getCredentialsForIdentity()
AWS.config.credentials.refresh((error) => {
if (error) {
console.error(error)
} else {
// Instantiate aws sdk service objects now that the credentials have been updated.
// example: var s3 = new AWS.S3();
console.log('Successfully logged!')
setUser(cognitoUser)
// history.push('/dash')
}
})
},
onFailure: function (err) {
alert(err.message || JSON.stringify(err))
},
})
}