自定义授权者的AWS API网关403错误

时间:2020-07-27 06:33:23

标签: amazon-web-services aws-lambda aws-api-gateway lambda-authorizer claudiajs

我正在使用Claudia-api-builder创建和部署。 https://github.com/claudiajs/example-projects/tree/master/custom-authorizers

我的AWS定制授权者如下所示:

let jwtDecode = require('jwt-decode');

var generatePolicy = function (authToken, methodArn) {
    'use strict';
    var tmp = methodArn.split(':'),
    apiGatewayArnTmp = tmp[5].split('/'),
    awsAccountId = tmp[4],
    region = tmp[3],
    restApiId = apiGatewayArnTmp[0],
    stage = apiGatewayArnTmp[1];
    let group = jwtDecode(authToken)["cognito:groups"];

if (group[0] === 'Admin') {
        return {
            'principalId': authToken.split('-')[0],
            'policyDocument': {
                'Version': '2012-10-17',
                'Statement': [{
                    'Effect': 'Allow',
                    'Action': [
                        'execute-api:Invoke'
                    ],
                    'Resource': [
                        'arn:aws:execute-api:' + region + ':' + awsAccountId + ':' + restApiId + '/' + stage + '/GET/citizens',
                        'arn:aws:execute-api:' + region + ':' + awsAccountId + ':' + restApiId + '/' + stage + '/GET/citizens/{citizenId}/personal-details'
                    ]
                }]
            }
        };
    }


exports.auth = function testAuth(event, context, callback) {
    'use strict';
    console.log('got event', event);

    /*
     * {
     * "type":"TOKEN",
     * "authorizationToken":"<Incoming bearer token>",
     * "methodArn":"arn:aws:execute-api:<Region id>:<Account id>:<API id>/<Stage>/<Method>/<Resource path>"
     * }
     */
    if (event && event.authorizationToken && event.methodArn) {
        callback(null, generatePolicy(event.authorizationToken, event.methodArn));
    } else {
        callback('Unauthorized');
    }
};

该资源中的第一个API运行正常,但是当我调用第二个API时:

'arn:aws:execute-api:' + region + ':' + awsAccountId + ':' + restApiId + '/' + stage + '/GET/citizens/{citizenId}/personal-details'

它给我403禁止使用:

{
    "Message": "User is not authorized to access this resource"
}

就我而言,授权缓存也被禁用

这个问题有解决方案吗?

1 个答案:

答案 0 :(得分:1)

该资源不应是API网关方法的路径。

实际上,它应该是资源的Arn。您可以通过执行以下操作从AWS控制台获取此信息:

  • 打开API网关
  • 选择您的API网关
  • 点击Resources选项
  • 找到您的资源(这将是GET下的citizens/{citizenId}/personal-details方法)。点击它。
  • 将为您提供Arn

使用基于路径的参数时,任何参数都将被*替换,因此将变为以下参数。

'arn:aws:execute-api:' + region + ':' + awsAccountId + ':' + restApiId + '/' + stage + '/GET/citizens/*/personal-details'