aws-lambdaaws-api-gatewayaws-samlambda-authorizer

Getting 403 while the authorizer response is cached


I have two lambda functions (A & B) that use the same LambdaTokenAuthorizer which is configured with the following identity

Identity:
    Header: Authorization
    ValidationExpression: Bearer.*
    ReauthorizeEvery: 30 # cache for 30 s

First and subsequent requests (to A) are authorized and resolve correctly, but any requests to B that come after and while the authorizer response is cached (from previous requests to A), will fail with 403 and the following message:

{ message: "User is not authorized to access this resource" }

Is this the expected behaviour? I couldn't find anything about it in the docs.

Is a default authorizer (that, by the way, is cached for 300s by default) even an option or is it an anti-pattern?

Are there ways around this (other than setting ReauthorizeEvery: 0)?

Is it correct to assume that if an authorizer is shared, then it should never cache the response?

Edit: I know this was "answered" before, but the documentation doesn't say anything about how the caching works. I would expect the authorizer not use the cache if the requested resource is different.


Solution

  • Most probable reason for this is the Authorizer output. You would be generating an output from the Authorizer that looks something like this -

    {
        "principalId": "some-id",
        "policyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Action": "execute-api:Invoke",
                    "Effect": "Allow",
                    "Resource": "arn:aws:execute-api:xx-region-1:123456789012:abc/test/GET/lambdaA"
            ]
        }
    }
    

    Notice the Resource attribute above. You are probably being very specific in allowing the Lambda function by specifying the ARN of Lambda A or Lambda B (Maybe you are dynamically generating it based on some inputs). Try changing it to

    "Resource": "*"
    

    Because you are using the same Authorizer for two different Lambda functions and you are using caching, you need to ensure that the output of the Authorizer allows execution of both the Lambda functions.

    Is a default authorizer (that, by the way, is cached for 300s by default) even an option or is it an anti-pattern?

    Definitely Not. Using a common Authorizer for multiple functions reduces a lot of maintenance overhead. Any change in the core authentication logic needs to be deployed only once with this approach.

    Is it correct to assume that if an authorizer is shared, then it should never cache the response?

    No. We can cache the responses even if the authorizer is shared. This ensures that if a user was authenticated to access ServiceA.FunctionA, he/she can access any other function of ServiceA without checking their authentication again.