Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 810
dReAmEr Avatar asked Sep 11 '26 11:09

dReAmEr


1 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");
}
like image 199
user2681304 Avatar answered Sep 13 '26 02:09

user2681304



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!