When use AWS API gateway with lambda authorizer, you may get 403 Forbidden
error code with the error message User is not authorized to access this resource
.
If you find out that this happens, but after some time, it goes away, then it might because of caching issue. For details reason, you can check out this wiki page: Why is my API Gateway proxy resource with a Lambda authorizer that has caching activated returning HTTP 403 "User is not authorized to access this resource" errors?.
The IAM policy is like below:
{
"principalId": "<YourPrincipalId>", // The principal user identification associated with the token sent by the client.
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow",
"Resource": "arn:aws:execute-api:{regionId}:{accountId}:{apiId}/{stage}/{httpVerb}/[{resource}/[{child-resources}]]"
}
]
},
}
One of the solution is to make the Resource
to be *
directly, but this might not be very safe, because we don't want to allow every resource.
The better solution is to allow everything after the {apiId}
, like below:
{
"principalId": "<YourPrincipalId>", // The principal user identification associated with the token sent by the client.
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow",
"Resource": "arn:aws:execute-api:{regionId}:{accountId}:{apiId}/*/*"
}
]
},
}
So you can just add a few line codes in your custom lambda authorizer function like below:
# Construct a wildcard "Resource" variable
tmp = event["methodArn"].split(':')
apiGatewayArnTmp = tmp[5].split('/')
resource = tmp[0] + ":" + tmp[1] + ":" + tmp[2] + ":" + tmp[3] + ":" + tmp[4] + ":" + apiGatewayArnTmp[0] + '/*/*'
References: