Search code examples
amazon-web-serviceslambdaaws-lambdaauth0

Maintain session state in AWS Lambda


How do I maintain session state in an AWS Lambda? For example, if I need to query DynamoDb for subscription information for a logged-in user, how do I do that from the Lambda function if the user is using an AngularJS web app?

I have the user logging in with Auth0 and a custom authorizer that verifies the user on AWS. But then I want to use the logged-in user's CognitoID to query the DynamoDB.

According to AWS documentation for Lambda (node.js) (https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html) you only have the Information about the Amazon Cognito identity provider when invoked through the AWS Mobile SDK.

identity.cognitoIdentityId

identity.cognitoIdentityPoolId

But what if I use a web app that uses AngularJS and Auth0?

Ok, maybe the simplest solution to store user info in the DynamoDB is just to extract the JWT on the client side, in AngularJS, and send the extracted Auth0 user_id —such as facebook|12345— along in the API request to the Lambda, which queries if the user exist in DynamoDB and if not creates a new record.

Then in each request to the API that has to query user info I send the user_id and in the Lambda I query the db with that id. It should be safe as I verify the users token in the Custom Authorizer and deny or allow the request before it hits the Lambda.


Solution

  • First of all Lambda is used as a stateless compute service. Therefore keeping session state in Lambda is not practical.

    Based on your scenario, you can send a request to API Gateway with the jwt token, where you can plugin a special Lambda function call Custom Authorizer, where you do the validation of the token and extract user id, which is then forwarded to the Business Logic Lambda function connected to the API Gateway endpoint. As you mentioned at Custom Authorizer you can query the user database and return more info to the Business Logic Lambda.

    If the token is not valid or expired you can return an error from Custom Authorizer Lambda function so the API Gateway sends back an error response without hitting the endpoint Lambda.

    In addition you can also cache the output of Custom Authorizer Lambda so that it will be cached for a given TTL for improved performance and reduced costs.