How to change error message in API authorizer in AWS?

Viewed 409

I am using Lambda for creating APIs for my project. I started using API Authorizer for Token Base Authentication. Below is my code:

import json, jwt
from datetime import datetime

def lambda_handler(event, context):
    timestamp = datetime.timestamp(datetime.now())
    
    decode_data=jwt.decode(jwt=event['authorizationToken'], key="", algorithms=["RS256"], options={"verify_signature": False})

    auth = 'Deny'
    if timestamp < decode_data['exp']:
        if decode_data['custom:user'] == 'Customer':
            auth = 'Allow'
 
    authResponse = { "principalId": "abc123", "policyDocument": { "Version": "2012-10-17", "Statement": [{"Action": "*", "Resource": "*", "Effect": auth}] }}
    return authResponse

I applied this authorizer with another Lambda for validation. So, it is working fine when token is valid, but when token get expired it give below message:

{
    "Message": "User is not authorized to access this resource with an explicit deny"
}

Now I want to customise this error and it status code also. How to do that? Any suggestion.

1 Answers

What you're seeing is indeed the error generated by the API Gateway. API Gateway will call your lambda in order to verify authorization after which you return a policy stating what the user is allowed to do, or not to do. API Gateway then uses this policy to determine the access you're allowed to have to the API.

Since you're returning an explicit DENY, you're getting this default error message from AWS. If you want to change this error message, you could experiment with returning a different result (e.g., an ALLOW for no actions or no resources, if that is at all accepted as response).

If you're using the new HTTP APIs (API Gateway V2) with payload format v2, you could also use their so-called simple response in which you don't have to return a policy at all. More information about this can be found here: Working with AWS Lambda authorizers for HTTP APIs .

Related