我正在使用Claudia api构建器来创建和部署。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时,I:e:
'arn:aws:execute-api:' + region + ':' + awsAccountId + ':' + restApiId + '/' + stage + '/GET/citizens/{citizenId}/personal-details'
它给了我403禁止与:
{
"Message": "User is not authorized to access this resource"
}
在我的情况下,授权缓存也被禁用
这个问题有什么解决方案吗?
资源不应该是API网关方法的路径。
事实上,它应该是资源的Arn。您可以通过执行以下操作从AWS控制台获取:
- 打开API网关
- 选择您的API网关
- 单击
Resources
选项 - 查找您的资源(这将是
citizens/{citizenId}/personal-details
下面的GET
方法(。点击它 - 将有一个
Arn
可供您使用
当使用基于路径的参数时,任何参数都会被*
替换,因此这将变成以下内容。
'arn:aws:execute-api:' + region + ':' + awsAccountId + ':' + restApiId + '/' + stage + '/GET/citizens/*/personal-details'
对我来说,解决方案是制作一个通配符资源,而不仅仅是将event.methodArn
传递到generateAllow()
中
外卡资源如下所示,然后将其传递到generateAllow()
中
var tmp = event.methodArn.split(':');
var apiGatewayArnTmp = tmp[5].split('/');
var resource = tmp[0] + ':' + tmp[1] + ':' + tmp[2] + ':' + tmp[3] + ':' + tmp[4] + ':' + apiGatewayArnTmp[0] + '/*/*';
generatePolicy("1", 'Allow', resource)
在这里可以找到更深入的解释https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-lambda-authorization-errors/