如何从API网关自定义授权者引发自定义错误消息 [英] How to throw custom error message from API Gateway custom authorizer

查看:120
本文介绍了如何从API网关自定义授权者引发自定义错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处表示,API网关将以401:未经授权的方式进行响应.

Here in the blue print says, API gateway will respond with 401: Unauthorized.

我在lambda中编写了相同的raise Exception('Unauthorized'),并且能够从Lambda Console对其进行测试.但是在POSTMAN中,我收到状态500 与身体:

I wrote the same raise Exception('Unauthorized') in my lambda and was able to test it from Lambda Console. But in POSTMAN, I'm receiving status 500 with body:

{
  message: null`
} 

我想添加自定义错误消息,例如无效签名","TokenExpired"等,不胜感激任何文档或指南.

I want to add custom error messages such as "Invalid signature", "TokenExpired", etc., Any documentation or guidance would be appreciated.

推荐答案

这完全有可能,但是文档如此糟糕且令人困惑.

This is totally possible but the docs are so bad and confusing.

这是您的操作方式:

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

There is an object called $context.authorizer that you have access to in your gateway responses template. You can read more about it here: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html

以下是从授权方lambda填充此authorizer对象的示例:

Here is an examample of populating this authorizer object from your authorizer lambda like so:

// 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;
        }

他们的关键是要添加此部分:

They key here is adding this part:

// 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上可用

This will become available on $context.authorizer

然后我在网关响应选项卡中设置正文映射模板,如下所示:

I then set the body mapping template in gateway responses tab like this:

{"message":"$context.authorizer.stringKey"}

注意:必须加引号!

最后-在以Authorization令牌设置为拒绝的邮递员中发送请求后,我现在从邮递员那里获得了一个如下所示的有效载荷:

finally - after sending a request in postman with Authorization token set to deny I now get back a payload from postman that looks like this:

{
    "message": "stringval custom anything can go here"
}

这篇关于如何从API网关自定义授权者引发自定义错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆