Search code examples
python-3.xaws-lambdaamazon-cognitoamazon-cognito-triggers

AWS Cognito Post authentication Lambda trigger - return NotAuthorizedException


I've implemented soft delete functionality with Cognito by marking a custom user status field as deleted. However, I need to catch login attempts and reject them in the Post authentication Lambda trigger as if they are unrecognized users. How do you do that in Python 3.9?

All I am getting is "Unrecognizable lambda output" and "InvalidLambdaResponseException" when I try to return an error.

I tried throwing an error or stuff along the lines of:

          return {
                    "body": json.dumps({}, default=str),
                    "statusCode": 400,
                    "headers": {
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Expose-Headers": "x-amzn-RequestId,x-amzn-ErrorType,x-amzn-ErrorMessage,Date",
                        # "Content-Length": "79",
                        "Content-Type": "application/x-amz-json-1.1",
                        # "Date": "Fri, 15 Nov 2024 19:14:19 GMT",
                        "X-Amzn-Errormessage": "Incorrect username or password.",
                        "X-Amzn-Errortype": "NotAuthorizedException:",
                        "X-Amzn-Requestid": context.aws_request_id
                    }
                }

Solution

  • I think the feature you're actually looking for is enabling/disabling users. There's no need to build your own solution using Lambda triggers, this is available out of the box.

    You can use the AdminDisableUser API to deactivate a specific user, which prevents them from logging in, which can effectively become a soft-delete. If you want, you can still add a custom attribute to make it more explicit.

    If you want to undo the soft delete, you just use AdminEnableUser to reactivate them.

    Since you're using Python, here are the corresponding boto3 docs: