问题描述: 在使用AWS API Gateway + Cognito + Lambda时,$context.authorizer.principalId为空。
解决方法:
确保在API Gateway的资源方法中正确配置了Cognito身份池作为身份验证器。
确保在Lambda函数中使用了event.requestContext.authorizer.principalId来获取用户的身份标识。
代码示例: 以下是一个Lambda函数的示例代码,可以从event对象中获取$context.authorizer.principalId。
exports.handler = async (event) => {
const principalId = event.requestContext.authorizer.principalId;
console.log('principalId:', principalId);
// 其他处理逻辑...
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
在上述代码中,event.requestContext.authorizer.principalId用于获取Cognito身份验证器提供的用户身份标识。
确保在API Gateway的资源方法中将Cognito身份池作为身份验证器配置,以便正确传递身份信息到Lambda函数中。
请注意,如果用户未经过身份验证或未提供有效的Cognito身份标识,$context.authorizer.principalId可能为空。因此,在处理逻辑中应该进行相应的检查和处理。