简体   繁体   中英

How to return 401 from AWS lambda authorizer without raising an exception

I have a lambda authorizer that is written in Python.

I know that with the following access policy I can return 200/403 :

{
        "principalId": "yyyyyyyy",
        "policyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Action": "execute-api:Invoke",
                    "Effect": "Deny",
                    "Resource": "*"
                }
            ]
        },
        "context": {
            "stringKey": "value",
            "numberKey": "1",
            "booleanKey": "true"
        },
        "usageIdentifierKey": "{api-key}"
    }

I'm trying to return 401 error if the customer didn't send any token, therefore I'm raising an exception :

raise Exception("Unauthorized")

The problem with this solution is that the AWS lambda fails and then the execution is marked as a failed execution and not as a successful execution of the lambda. Is there any way to return 401 without failing the lambda ?

Also tried the following like in lambda integration but didn't work:

return  {"statusCode": 401, "body" : "Unauthorized"}

It really is ugly, but that's the only way to truly signal a 401, which means "I can't find your Authorization header or cookie or nothing, you have to authenticate to do that". A 403 is an explicit 👎 saying "I know who you are, you're Forbidden from doing that". It's an odd, ternary response that API Gateway needs here: 👍/👎/🤷, and this "throw a very specific exception" is one way to do it.

So you can't customize the response with the authorizer lambda; you can only give a response document that says yay/nay, or throw your hands up and signal "I can't find any authentication material here". To customize the shape of that response to a client, you would use Gateway Responses . With this, you can customize the shape of the json (or whatever content-type, really) of your 401/403 responses.

Now, with respect to raise Exception("Unauthorized") polluting your metrics, making ambiguous real errors vs this expected error, I agree, it kinda stinks. My only recommendation would be to log something ERROR level that you set up a Metric Filter to watch out for, and use that as your true "something's gone wrong" metric.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM