一段时间以来,我一直在努力寻找这个问题的答案,因为在线上的任何这些线程都没有任何简明的回答。
在用户使用自定义属性针对您的 Cognito 用户池拥有 Authenticated 凭据后,您似乎正在尝试提出有效的 Authorization 策略。
我创建了一个库,用于导出一些函数,这些函数允许我为 authenticated 用户捕获 UserPoolId 和 Username,以便我可以捕获 custom:<attribute> 我需要在我的 lambda 中,以便我已实现的条件可以将 API 用于我需要为我的应用身份验证的每个用户提供授权的其余 AWS 服务。
这是我的图书馆:
import AWS from "aws-sdk";
// ensure correct AWS region is set
AWS.config.update({
region: "us-east-2"
});
// function will parse the user pool id from a string
export function parseUserPoolId(str) {
let regex = /[^[/]+(?=,)/g;
let match = regex.exec(str)[0].toString();
console.log("Here is the user pool id: ", match);
return match.toString();
}
// function will parse the username from a string
export function parseUserName(str) {
let regex = /[a-z,A-Z,0-9,-]+(?![^:]*:)/g;
let match = regex.exec(str)[0].toString();
console.log("Here is the username: ", match);
return match.toString();
}
// function retries UserAttributes array from cognito
export function getCustomUserAttributes(upid, un) {
// instantiate the cognito IdP
const cognito = new AWS.CognitoIdentityServiceProvider({
apiVersion: "2016-04-18"
});
const params = {
UserPoolId: upid,
Username: un
};
console.log("UserPoolId....: ", params.UserPoolId);
console.log("Username....: ", params.Username);
try {
const getUser = cognito.adminGetUser(params).promise();
console.log("GET USER....: ", getUser);
// return all of the attributes from cognito
return getUser;
} catch (err) {
console.log("ERROR in getCustomUserAttributes....: ", err.message);
return err;
}
}
实现了这个库后,它现在可以被您需要为其创建授权策略的任何 lambda 使用。
在你的 lambda 中,你需要导入上面的库(我省略了下面的导入语句,你需要添加它们以便访问导出的函数),你可以这样实现它们的使用::
export async function main(event, context) {
const upId = parseUserPoolId(
event.requestContext.identity.cognitoAuthenticationProvider
);
// Step 2 --> Get the UserName from the requestContext
const usrnm = parseUserName(
event.requestContext.identity.cognitoAuthenticationProvider
);
// Request body is passed to a json encoded string in
// the 'event.body'
const data = JSON.parse(event.body);
try {
// TODO: Make separate lambda for AUTHORIZATION
let res = await getCustomUserAttributes(upId, usrnm);
console.log("THIS IS THE custom:primaryAccountId: ", res.UserAttributes[4].Value);
console.log("THIS IS THE custom:ROLE: ", res.UserAttributes[3].Value);
console.log("THIS IS THE custom:userName: ", res.UserAttributes[1].Value);
const primaryAccountId = res.UserAttributes[4].Value;
} catch (err) {
// eslint-disable-next-line
console.log("This call failed to getattributes");
return failure({
status: false
});
}
}
来自 Cognito 的响应将提供一个包含您需要的自定义属性的数组。 Console.log 使用 console.log("THIS IS THE Cognito response: ", res.UserAttributes); 记录来自 Cognito 的响应,并检查 CloudWatch 日志中所需属性的索引号并调整所需的索引:
res.UserAttributes[n]
现在您有一个authorization 机制,您可以在 lambda 中使用该机制以允许用户发布到 DynamoDB,或使用您的应用程序中的任何其他 AWS 服务,并为每个经过身份验证的用户提供正确的授权。
在您可以在 res.UserAttributes[n] 中看到的响应中,您将看到 sub 的属性,这是您正在寻找的。p>