Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom authorizers in Amazon API Gateway 500 error

I use Serverless-Authentication-boilerplate and want to map custom error response. But it always return 500 error.

authorize.js

// Authorize
function authorize(event, callback) {
  let providerConfig = config(event);
  try {
    let data = utils.readToken(event.authorizationToken, providerConfig.token_secret);
    console.log("Decrypted data: " + JSON.stringify(data));

    let methodArn = event.methodArn.replace(/(GET|POST|PUT|DELETE)/g, '*').replace(/mgnt.+/g, 'mgnt/*');

    console.log(`Change methodArn to: ${methodArn}`);

    // TODO: handle expiration time validation
    callback(null, utils.generatePolicy(
      data.id, // which is $context.authorizer.principalId
      'Allow',
      methodArn));
  } catch (err) {
    console.log(err);
    callback('401 Unauthenticated');
  }
}

s-function.json

responses:{ 
  "401 Unauthenticated.*": {
      "statusCode": "401"
  },
  "default": {
      "statusCode": "200",
      "responseModels": {
        "application/json;charset=UTF-8": "Empty"
      },
      "responseTemplates": {
        "application/json;charset=UTF-8": ""
      }
  }
}
like image 456
Jim Avatar asked Jul 29 '16 03:07

Jim


People also ask

Which custom authorizers are supported by API gateway?

A Lambda authorizer (formerly known as a custom authorizer) is an API Gateway feature that uses a Lambda function to control access to your API.

How do I return custom HTTP status codes from a lambda function in Amazon API gateway?

The easiest way to set custom HTTP status code is to setup a Lambda Proxy Integration in API Gateway. In API Gateway > Resource > Actions Dropdown > Create Method > tick Lambda Proxy Integration and select appropriate Lambda function. For async functions just return with an object with statusCode and body .


1 Answers

After ask to Amazon Web Services.

Unfortunately the mapping of the Authorizer is not currently configurable and every returned error from a lambda function will map to a 500 status code in API gateway. Moreover, the mapping is performed on an exact string match of the output, so, in order to return the intended 401 Error to the client, you should execute a call to 'context.fail('Unauthorized');.

Finally, I change

callback('401 Unauthenticated');

to

context.fail('Unauthorized');

and work fine.

Sharing to whom may encounter this.

like image 190
Jim Avatar answered Sep 21 '22 12:09

Jim