Return 401 Unauthorized Response when using Lambda Authorizer with API Gateway

0

I'm finding a way to return 401 error from Lambda Authorizer, my Lambda function is implemented with Typescript, and I'm using async function (it's required because my function use some packages which return Promise object). I already tried the way from docs: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html

case 'unauthorized':
            callback('Unauthorized');   // Return a 401 Unauthorized response
            break;

And from here https://github.com/awslabs/aws-apigateway-lambda-authorizer-blueprints/blob/master/blueprints/nodejs/index.js

callback("Unauthorized", null);

I also tried the solution

throw new Error('Unauthorized')

But all the ways return the 500 Internal Server Error instead of 401 error

2回答
0

Hi , You can try official docs help or

import { Handler, APIGatewayAuthorizerResult } from 'aws-lambda';

export const handler: Handler = async (event, context, callback): Promise<APIGatewayAuthorizerResult> => {
    try {
        // 1. Your authorization logic (using awaited Promises if needed)
        const token = event.authorizationToken; 
        if (!token || !await isValidToken(token)) {
            return { 
                principalId: 'user', // Arbitrary value
                policyDocument: {
                    Version: '2012-10-17',
                    Statement: [{
                        Action: 'execute-api:Invoke',
                        Effect: 'Deny',
                        Resource: event.methodArn 
                    }]
                }
            }; 
        }

        // 2. Successful authorization - Return an Allow policy
        return { 
            principalId: 'user', // Identify the user 
            policyDocument: {
                Version: '2012-10-17',
                Statement: [{
                    Action: 'execute-api:Invoke',
                    Effect: 'Allow',
                    Resource: event.methodArn 
                }]
            }
        }; 

    } catch (error) {
        console.error('Authorization error:', error);
        // For simplicity, handle errors as Unauthorized
        callback('Unauthorized'); 
    }
};

// Helper function for your token validation logic
async function isValidToken(token: string): Promise<boolean> {
    // Your token validation logic here
    // ...
}

Authorization Logic: Replace isValidToken with your actual token validation logic (which can now be asynchronous using await). Deny Policy: If authorization fails, return an IAM policy document with a 'Deny' effect. Ensure the Resource matches the method ARN of your API Gateway method. Allow Policy: If authorization succeeds, return an IAM policy document with an 'Allow' effect. Error Handling: Wrap your logic in a try...catch block. For simplicity, we log the error and then return an 'Unauthorized' string. You can adjust error handling for more specific responses, if desired.

i used content from aws docs that i found on github and some from huggingface...hope it helps

回答済み 3ヶ月前
0

You could look into this guide for general troubleshooting: https://repost.aws/knowledge-center/api-gateway-401-error-lambda-authorizer.

From your description could be that you need to “block” those asynchronous processes by awaiting them inside the lambda handler.

profile picture
エキスパート
回答済み 3ヶ月前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ