简体   繁体   中英

Custom error message on response in serverless

I am using node js serverless v2 framework. I have come to know that callback only accept Allow, Deny and Unauthorized as parameter. I am using custom authorizer for resource protection. I need to send custom error message on callback which i am not able to achieve. Here are the list of ways I tried but failed

piece of code

if (!response.data) {
    return callback(null, generateAuthResponse(decoded.id, 'Deny', methodArn));
}
if (response.data && response.data.status === 'active') {
    return callback(null, generateAuthResponse(decoded.id, 'Allow', methodArn));
}
if (response.data && response.data.status == 'inactive') {
    return callback(null, generateAuthResponse(decoded.id, 'Deny', methodArn));
}

Instead of return callback(null, generateAuthResponse(decoded.id, 'Deny', methodArn)); deny i want to send custom error message.

#1

return callback(null, "Session expired");

#2

return callback(null, {
            statusCode: 403,
            headers: {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Headers': 'Content-Type',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
                'Access-Control-Allow-Credentials': true,
            },
            body: JSON.stringify({
                error: error
            })
        }); 

#3

return {
                statusCode: 403,
                headers: {
                    'Content-Type': 'application/json',
                    'Access-Control-Allow-Headers': 'Content-Type',
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Methods': 'OPTIONS,POST,GET',
                    'Access-Control-Allow-Credentials': true,
                },
                body: JSON.stringify({
                    error: error
                })
            }

#4

throw Error('Session expired')

All are either throwing cors error with x-amzn-errortype: AuthorizerConfigurationException or rejecting (Invoking error). is there way to send custom error response?

Most Likely some syntax error.

Try this:

    let response_object = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        },
        body: JSON.stringify("Some Custom Error")
    };
    return response_object;

Create and setup resource for ACCESS_DENIED response with ResponseTemplates .

serverless.yml

...
resources:
  Resources:
    DenyFailureGatewayResponse:
      Type: 'AWS::ApiGateway::GatewayResponse'
      Properties:
        ResponseParameters:
          # Config your header response
          gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
          gatewayresponse.header.Access-Control-Allow-Headers: "'*'"
        ResponseTemplates:
            # Custom response object
            application/json: |
              {
                "success":false,
                "message":"$context.authorizer.errorMessage"
              }
        # Setup only for ACCESS_DENIED type
        ResponseType: ACCESS_DENIED
        RestApiId:
          Ref: 'ApiGatewayRestApi'
        StatusCode: '403'
...

And in your generateAuthResponse function, let update your authResponse object if you need a custom message.

const generateAuthResponse = (principalId, effect, resource, errorMessage = null) => { // I guest function will look like that
  // ... do something

  // before return, let custom your error message
  if(effect.toLowerCase() === 'deny' && errorMessage !== null){
    authResponse.context = {
      // Key to map with $context.authorizer.errorMessage
      "errorMessage": errorMessage ,
    };
  }

  return authResponse;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM