dReAmEr
dReAmEr

Reputation: 7196

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

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.

Upvotes: 3

Views: 1617

Answers (2)

user2681304
user2681304

Reputation: 129

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");
}

Upvotes: 1

ejohnson
ejohnson

Reputation: 711

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

Upvotes: 0

Related Questions