gpt4 book ai didi

aws-api-gateway - 如何从 API Gateway 自定义授权方抛出自定义错误消息

转载 作者:行者123 更新时间:2023-12-03 22:18:50 25 4
gpt4 key购买 nike

Here蓝图中说,API 网关将响应 401: Unauthorized。

我写了同样的raise Exception('Unauthorized')在我的 lambda 中,并且能够从 Lambda 控制台对其进行测试。但是在 postman 中,我收到状态 500与 body :

{
message: null`
}

我想添加自定义错误消息,例如“无效签名”、“TokenExpired”等,将不胜感激任何文档或指导。

最佳答案

这是完全可能的,但文档是如此糟糕和令人困惑。

这是你如何做到的:

有一个对象叫 $context.authorizer您可以在网关响应模板中访问。您可以在此处阅读更多相关信息:https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html

这是填充此 authorizer 的示例来自您的授权方 lambda 的对象,如下所示:

// A simple TOKEN authorizer example to demonstrate how to use an authorization token 
// to allow or deny a request. In this example, the caller named 'user' is allowed to invoke
// a request if the client-supplied token value is 'allow'. The caller is not allowed to invoke
// the request if the token value is 'deny'. If the token value is 'Unauthorized', the function
// returns the 'Unauthorized' error with an HTTP status code of 401. For any other token value,
// the authorizer returns an 'Invalid token' error.

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");
}
};

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 custom anything can go here",
"numberKey": 123,
"booleanKey": true,
};
return authResponse;
}


他们在这里的关键是添加这部分:
// Optional output with custom properties of the String, Number or Boolean type.

authResponse.context = {
"stringKey": "stringval custom anything can go here",
"numberKey": 123,
"booleanKey": true,
};

这将在 $context.authorizer 上可用

然后我在网关响应选项卡中设置正文映射模板,如下所示:
{"message":"$context.authorizer.stringKey"}

注意 : 必须引用!

最后 - 在 postman 发送请求后 Authorization token 设置为拒绝我现在从 postman 那里得到一个有效载荷,如下所示:
{
"message": "stringval custom anything can go here"
}

关于aws-api-gateway - 如何从 API Gateway 自定义授权方抛出自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47921803/

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