我想使用JavaScript API调用Lambda函数。是否可以使用cognito用户池身份调用Lambda函数?
我希望使用在浏览器上进行身份验证的用户的cognito用户池凭据来调用它。
目标是Lambda函数将具有与来自cognito用户池的用户相同级别的S3访问权限。
我该怎么做?
感谢
我想使用JavaScript API调用Lambda函数。是否可以使用cognito用户池身份调用Lambda函数?
我希望使用在浏览器上进行身份验证的用户的cognito用户池凭据来调用它。
目标是Lambda函数将具有与来自cognito用户池的用户相同级别的S3访问权限。
我该怎么做?
感谢
你可以通过建立联盟用户池令牌Cognito联合身份,这会给你的临时AWS凭据调用AWS lambda表达式。您将需要创建身份池并创建一个具有权限的角色lambda:InvokeFunction。
另外请记住,如果您选择基于身份验证角色的解决方案,如果要将其限制为用户子集,则用户池的所有用户都将能够调用lambda函数,您可以使用用户池中的组和以联合身份标识或基于规则的映射来确定角色。
你需要这三个包:
<script src="js/aws-cognito-sdk.min.js"></script>
<script src="js/amazon-cognito-identity.min.js"></script>
<script src="js/aws-sdk.min.js"></script>
一旦你登录使用Cognito,你可以调用lambda函数是这样的:
function invokeMyLambda()
{
if(!objCognitoUser) syncAwsFromCognito();
var lambda = new AWS.Lambda({region: 'us-east-1', apiVersion: '2015-03-31'});
// create JSON object for service call parameters
var pullParams = {
FunctionName : 'myLambFunctionName',
InvocationType : 'RequestResponse', // Event | RequestResponse | DryRun
LogType : 'None',
Payload : JSON.stringify({ "yourKeyName": "Key Value to pass to the function in Event Object"}),
};
// invoke Lambda function, passing JSON object
lambda.invoke(pullParams, function(err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
alert("Success: " + JSON.stringify(data));
}
});
lambda = null;
}
function syncAwsFromCognito() {
// objCognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
if(!objCognitoUser) {
objCognitoUser = objUserPool.getCurrentUser();
}
if (objCognitoUser) {
objCognitoUser.getSession(function(err, result) {
if (result) {
if(AWS.config.credentials == null) // Refresh AWS Config credentials
AWS.config.credentials = new AWS.CognitoIdentityCredentials(jsonUserCreds);
AWS.config.credentials.params.Logins[strConfUserPoolID] = result.idToken.jwtToken;
}
});
//call refresh method in order to authenticate user and get new temp credentials
AWS.config.credentials.refresh(function (error) {
if (error) {
console.log('syncAwsFromCognito', error);
}
});
}
else
alert("Session expired. Login again");
}
可以使S3在Cognito认证完成后直接从Javascript调用。我更喜欢将REST API与API网关一起使用,而不是使用来自浏览器的直接Lambda函数调用。这是因为即使您使用Cognito SDK注销,Lambda函数调用也依赖于TokenID,该TokenID在一个小时内有效。