Reputation: 1742
I have some data stored in DynamoDB. In order to retrieve the data, I'm requiring users to be authenticated against Cognito user pool. I have managed to authenticate users successfully using AWS-Amplify library and Cognito returns following JSON data after successful authentication :
{
"username":"....",
"pool":{
"userPoolId":"....",
"clientId":"...",
"client":{
"endpoint":"....",
"userAgent":"aws-amplify/0.1.x js"
},
"advancedSecurityDataCollectionFlag":true,
"storage":{
"loglevel:webpack-dev-server":"INFO"
}
},
"Session":"abcd12345", <-------------------------------------------
"client":{
"endpoint":"......",
"userAgent":"aws-amplify/0.1.x js"
},
"signInUserSession":null,
"authenticationFlowType":"USER_SRP_AUTH",
"storage":{
"loglevel:webpack-dev-server":"INFO"
},
"challengeName":"NEW_PASSWORD_REQUIRED",
"challengeParam":{
"userAttributes":{
"email_verified":"true",
"phone_number_verified":"true",
"phone_number":"...",
"email":"....."
},
"requiredAttributes":[
]
}
}
I have implemented Lambda function with API Gateway to handle data request from client. My question is, is there a way to validate the session value ( returns by Cognito ) inside Lambda function, so that I can ensure user is authenticated before I return data?
Upvotes: 0
Views: 1720
Reputation: 2748
May be you found a solution to this, then I hope it will help someone else.
If I got your question correctly you can use AWS.CognitoIdentityServiceProvider
and do it this way:
const AWS = require('aws-sdk');
const cisp = new AWS.CognitoIdentityServiceProvider({ apiVersion: '2016-04-18'});
exports.handler = (event, context, callback) => {
const accessToken = event.accessToken;
const cispParams = {
"AccessToken": accessToken
};
cisp.getUser(cispParams, (err, result) => {
if (err) {
console.log(err);
callback(err);
} else {
// code in this part is reached only if accessToken is valid.
// So add your code to respond to a verified user here.
}
// rest of your Lambda code.
But accessToken will not be there by default. You have to pass it from front end.
//your code to generate API Gateway url//
+ '?accessToken=' + session.getAccessToken().getJwtToken();
Then setup API Gateway to pass it to Lambda (can search for how to pass url params to Lambda through API Gateway).
Upvotes: 2