#446·examples

How to pass expire token error in custom authoriser for API gateway response

Author: dilippatidar123Created Oct 15, 2019Updated Feb 27, 2024

Hi Team, We are using following configuration. Lambda :-

exports.handler =  async (event, context, callback) => {
    try {
        callback(null,policyData);
        return;
    } catch (err) {
      // Always accepts "Unauthorized".
        callback("Unauthorized");
        return;
    }
};

SAM template :-

ExpiredGatewayResponse:
    Type: 'AWS::ApiGateway::GatewayResponse'
    Properties:
      ResponseParameters:
        gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
        gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
      ResponseType: EXPIRED_TOKEN
      ResponseTemplates:
        application/json: |
          {
            "success":false,
            "message":"Token Expired"
          }
      RestApiId: !Ref ApiGatewayApi
      StatusCode: '401'
  AuthFailureGatewayResponse:
    Type: 'AWS::ApiGateway::GatewayResponse'
    Properties:
      ResponseParameters:
        gatewayresponse.header.Access-Control-Allow-Credentials: "'true'"
        gatewayresponse.header.Access-Control-Allow-Origin: !Ref CorsOriginUrl
        gatewayresponse.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
      ResponseType: UNAUTHORIZED
      RestApiId: !Ref ApiGatewayApi
      StatusCode: '401'

In above code its always return unauthorized error. If we pass anything else other then "Unauthorized" in call back then its return the error (message:null).

Please suggest how can we pass any other error response type like expired token form custom authorizer and In SAM it will take the configuration "ExpiredGatewayResponse".

Thanks, Dilip