通常情况下,这个问题是由于Lambda Authorizer没有正确与API Gateway集成造成的。要解决这个问题,可以按照以下步骤进行:
1.打开API Gateway控制台,选择你的API。 2.从左侧菜单中选择“资源”,然后选择一个要设置授权的资源。 3.在资源设置页的“方法请求”选项卡中,确保“授权”下拉框中选择的是你的Lambda Authorizer函数。 4.保存更改并尝试再次调用API。
以下提供一段示例代码,可以给出如何在创建API时正确设计Lambda Authorizer及其集成的步骤:
const AWS = require('aws-sdk');
exports.handler = async (event, context, callback) => { const token = event.authorizationToken;
try {
/* Authenticate token here */
const policy = generatePolicy('user', 'Allow', event.methodArn);
callback(null, policy);
} catch (e) {
callback('Unauthorized');
}
};
function generatePolicy(principalId, effect, resource) { const authResponse = {};
authResponse.principalId = principalId;
if (effect && resource) {
const policyDocument = {};
const statementOne = {};
const policyStatements = [];
statementOne.Action = 'execute-api:Invoke';
statementOne.Effect = effect;
statementOne.Resource = resource;
policyStatements.push(statementOne);
policyDocument.Version = '2012-10-17';
policyDocument.Statement = policyStatements;
authResponse.policyDocument = policyDocument;
}
return authResponse;
}