我将如何在另一个帐户中授予 lambda 函数访问权限以在 cognito 用户池中创建用户?
到目前为止我已经尝试过:
const cognitoProcessorRolePrincipal = new AccountPrincipal(getEnvVars(this).THE_OTHER_ACCOUNT);
const cognitoProcessorRole = new Role(this, `${getEnvWithApp(this)}-cognito-processor-role`, {
assumedBy: cognitoProcessorRolePrincipal,
roleName: `${getEnvWithApp(this)}-cognito-processor-role`,
inlinePolicies: {
cognitoPolicy: new PolicyDocument({
statements: [new PolicyStatement({
effect: Effect.ALLOW,
actions: [
"cognito-idp:AdminCreateUser",
],
resources: [this.userPool.userPoolArn]
})]
})
}
})
但我不断从其他服务收到此错误。因此角色被正确承担,但没有创建用户的权限。
"AccessDeniedException: User: arn:aws:sts::OMITEDcognito-processor-role/OMITED is not authorized to perform: cognito-idp:AdminCreateUser on resource: arn:aws:cognito-idp:us-west-1:OMITED:userpool/OMITED because no identity-based policy allows the cognito-idp:AdminCreateUser action\n\tstatus code: 400, request id: OMITED"
我已经尝试过授予这样的权利,
this.userPool.grant(cognitoProcessorRole,
"cognito-idp:AdminCreateUser",
)
但无济于事。
在拥有 cognito 实例的帐户上,您需要创建一个角色来授予另一个帐户访问它的权限:
new Role(this, 'allowOtherAccountRole', {
roleName: 'TheRoleName',
assumedBy: new AccountPrincipal(accountId), // <~ put the account id of the other account here
inlinePolicies: { delegation: new PolicyDocument({
statements: [
...
]
})
}
});
陈述是这样的
const allowAll = new PolicyStatement();
allowAll.addActions('cognito:*');
allowAll.addResources('the:cognito:arn:here');
statements.push(allowAll);
现在在另一个帐户(想要访问另一个帐户的cognito的帐户)上,您需要使用STS来承担角色:
const { Credentials } = await this.sts.assumeRole({
RoleArn: `arn:aws:iam::${theCognitoAccountId}:role/TheRoleName`,
RoleSessionName: `cross-account-${Date.now()}`
});
并使用
Credentials
配置 Cognito 客户端。
另外,请记住授予 lambda 权限来承担此角色。
const allowAssumeRole = new PolicyStatement();
allowAssumeRole.addActions('sts:AssumeRole');
allowAssumeRole.addResources(`arn:aws:iam::${theCognitoAccountId}:role/TheRoleName`);
lambda.role.addToPrincipalPolicy(allowAssumeRole);