gpt4 book ai didi

node.js - Lambda 授权方未在 node.js 中使用回调()返回正确的错误消息

转载 作者:搜寻专家 更新时间:2023-11-01 00:48:43 25 4
gpt4 key购买 nike

我在 AWS API 网关上创建了一个 Lambda 授权方,它调用了一个 Lambda 函数。以下是用 Node.js 8.0 代码编写的 Lambda 函数中的代码。

exports.handler =  function(event, context, callback) {
var token = event.authorizationToken;
switch (token.toLowerCase()) {
case 'allow':
callback(null, generatePolicy('user', 'Allow', event.methodArn));
break;
case 'deny':
callback(null, generatePolicy('user', 'Deny', event.methodArn));
break;
case 'unauthorized':
callback("Unauthorized"); // Return a 401 Unauthorized response
break;
default:
callback("Error: Invalid token");
}
};

// Help function to generate an IAM policy
var generatePolicy = function(principalId, effect, resource) {
var authResponse = {};

authResponse.principalId = principalId;
if (effect && resource) {
var policyDocument = {};
policyDocument.Version = '2012-10-17';
policyDocument.Statement = [];
var statementOne = {};
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
}

// Optional output with custom properties of the String, Number or Boolean type.
authResponse.context = {
"stringKey": "stringval",
"numberKey": 123,
"booleanKey": true
};
return authResponse;
}

(以上示例代码如果来自网站 https://markpollmann.com/lambda-authorizer/ )

如果我通过为 authorizationToken 传递无效值来保存并测试此函数,我会得到如下预期结果。

Response:
{
"errorMessage": "Error: Invalid token"
}

Request ID:
"e93567c0-fcbb-4cb1-b0b3-28e9c1b30162"

但是如果我从 Postman 调用这个 API,通过传递 header 中的值,我会得到以下响应。对于 header 中的任何值,即拒绝、允许、未授权、错误等,我都会收到此错误。

{
"message": null
}

postman 中的状态消息显示“500 Internal Server Error”。以下是 postman 标题部分的详细信息。

content-length →16
content-type →application/json
date →Fri, 08 Mar 2019 14:07:57 GMT
status →500
x-amz-apigw-id →W89kFDRDoEFxYg=
x-amzn-errortype →AuthorizerConfigurationException
x-amzn-requestid →92f31d11-41ab-11e9-9c36-97d38d96f31b

我不明白为什么 API 返回上述响应和错误消息,而 Lambda 测试工作正常。

我已经在 SO 中完成了以下两个线程,但答案/评论对我没有帮助。

AWS API Gateway with custom authorizer returns AuthorizerConfigurationException AWS API Gateway Custom Authorizer AuthorizerConfigurationException

最佳答案

我明白了为什么我收到无效输入的消息 = null 的原因。 switch case 中的默认 block 在 callback() 方法中使用参数“Error: Invalid token”。 API Gateway 仅将“允许”、“拒绝”和“未授权”识别为有效值。这些值也区分大小写。如果将这些值之外的任何字符串值传递给 callback() 方法,则 API 网关将向客户端返回 message=null。

关于node.js - Lambda 授权方未在 node.js 中使用回调()返回正确的错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55064760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com