我的应用程序是一个使用 2 项服务进行身份验证的过程,其中一项是 AWS Cognito。当用户通过身份验证时(Cognito 提供的 JWT token 也是如此),我尝试通过 AdminListGroupsForUser
API 调用列出该用户的组。我收到了 UserNotFoundException 这很奇怪,因为之前的调用刚刚使用相同的凭据验证了该用户?
我尝试了以下内容:
router.post("/groups/list", (req, res, next) => {
const { email, limit, nextToken } = req.body;
const listGroupsForUserParams = getAdminListGroupsForUserParams({
email,
limit,
nextToken
});
const getUserParams = getAdminGetUserParams(email);
cognitoClient.adminListGroupsForUser(listGroupsForUserParams, (listErr, listData) => {
cognitoClient.adminGetUser(getUserParams, (getErr, getData) => {
console.log(listErr); // "UserNotFoundException"
console.log(listData); // null
console.log(getErr); // null
console.log(getData); // User
});
});
});
listGroupsForUserParams
和 getUserParams
包含相同的信息,即:
{
UserPoolId: "...",
Username: "test@example.com" // I use email as Username
}
我不明白为什么前一个调用无法在池中找到用户而后者可以?
参见(供引用):
最佳答案
我遇到了同样的问题,出于某种原因,adminListGroupsForUser
函数不接受电子邮件作为用户名,而 adminGetUser
接受。
我通过使用 adminGetUser
检索用户数据来解决这个问题。它返回用户及其所有属性。检索名称为 sub
的属性值,并将其用作 adminListGroupsForUser
调用的用户名。
像这样:
const getParams = {
UserPoolId: "" /*put your user pool Id here*/,
Username: "" /* email */
};
cognitoidentityserviceprovider.adminGetUser(getParams, function(err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
return;
}
var sub;
if (data.UserAttributes && data.UserAttributes.length) {
for (var i = 0; i < data.UserAttributes.length; ++i) {
const attr = data.UserAttributes[i];
if (attr.Name === 'sub') {
console.log(attr);
sub = attr.Value
break;
}
}
}
if (!sub)
return;
const groupsParams = {
UserPoolId: event.userPoolId,
Username: sub
};
cognitoidentityserviceprovider.adminListGroupsForUser(groupsParams, function(err, data) {
/* Your code using groups here */
});
});
关于javascript - AdminListGroupsForUser 返回用户不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53393588/