How to return 401 ("Unauthorized") from AWS Lambda Authorizer

Viewed 780

We are using AWS Lambda Authorizer with API Gateway to protect our downstream API's.

Below is the code snippet from our Java based lambda authorizer

Statement statement = Statement.builder()
            .resource(input.getMethodArn()).effect(effect)
            .build();

    PolicyDocument policyDocument = PolicyDocument.builder()
            .statements(
                    Collections.singletonList(statement)
            ).build();

    return AuthorizerResponse.builder()
            .principalId(userId)
            .policyDocument(policyDocument)
            .context(ctx)
            .build();
  1. With correct token (effect = "Allow"): getting proper API response from API

  2. With incorrect token (effect = "Deny") Getting 403 HTTP response code.

We need 401 ("Unauthorized") as a response, Can someone pls help how to do this ? we have lambda authorizer written in java.

2 Answers

You can throw RuntimeException with Unauthorized message. One thing is to be in mind, you can not throw checked exception like Exception("Unauthorized"). Because handleRequest method signature of RequestHandler interface don't allow to do so.

if(isInvalidToken){
  throw new RuntimeException("Unauthorized");
}

Try throwing an exception with a message of "Unauthorized".

Related