amazon cognito + lambda + s3 + iam
TRANSCRIPT
Granting access to downloadable [paid]
resources in mobile appusing AWS Cognito + Lambda + IAM + S3
Goal● we have paid downloadable content (in the
form of JSON files on Amazon S3)● we need to give access to content from
mobile application to specific users
Options
● Using signed URLs in Amazon S3● Managing access with custom developed
backend
or
● Amazon Cognitor + Lambda + IAM + S3
Granting access to Quest
● each Quest is saved as Amazon S3 object in JSON format
● Objects are not accessible publicly● When user buys or open Quest in
application, we need to update Amazon IAM Role policy
Amazon IAM policy '{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::zequest*"],
"Condition": {
"StringEquals": {
"cognito-identity.amazonaws.com:sub": ["us-east-1:3abb829b-82c1-4ac5-85fa-4dc566c6acfb"]
}
}
}
]
}'
Content access is granted through Resource section
User is identified with Cognito IdentityId
1. User can be non-authenticated until “Go to quest” phase
2. Non-authenticated user is proposed to authenticate with Facebook/Twitter/Google+
3. Every user gets Cognito IdentityId (used in IAM policies)
1. User select content and click “Download” (running man icon on image)
2. Depending on content type (in-app purchase or free) user passes (or skip) payment phase
Update Amazon Cognito datasetAWS.config.region = 'us-east-1';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:123123123123123123123',
});
AWS.config.credentials.get(function() {
var syncClient = new AWS.CognitoSyncManager();
syncClient.openOrCreateDataset('quests', function(err, dataset) {
dataset.put('123456789', 'yourJSONValueForQuestData', function(err,
record){
dataset.synchronize({
onSuccess: function(data, newRecords) {
console.log("successful");
}
});
});
});
});
https://gist.github.com/werdan/3d8b7ad34cf60649a074
NB! Synchronizationis done only if there are changesin dataset
Amazon Cognito - Lambda events
● on Cognito dataset synchronization you can launch Amazon Lambda function
● This function, using AWS IAM API, updates Policy for authenticated user (using Cognito IdentityId)
● Amazon Lambda event handling is synchronous
Amazon Lambda pseudo-code
● get Cognito IdentityId● get current policy for this user● update policy with access to new Amazon
S3 object
Amazon Lambda example var AWS = require('aws-sdk');
var iam = new AWS.IAM();
var params = {
RoleName: 'Cognito_ZeQuestAuth_Role',
PolicyDocument: JSON.stringify(policy),
PolicyName: "us-east-1@3abb829b-82c1-4ac5-85fa-4dc56612313213"
};
iam.putRolePolicy(params, function(err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
});
Questions?
Andriy [email protected]: samilyakahttp://opsway.com