可以通过在Lambda Authorizer中使用自定义缓存来解决此问题。以下是一个基本的示例:
const cache = {};
exports.handler = async(event) => {
const token = event.authorizationToken;
// Check if the token is cached
if (cache[token]) {
return generatePolicy(cache[token].userId, 'Allow', event.methodArn);
}
// Perform authentication and authorization
const userId = await authenticateToken(token);
const authorized = await authorizeUser(userId, event);
// Cache the userId if authorized
if (authorized) {
cache[token] = {userId: userId};
return generatePolicy(userId, 'Allow', event.methodArn);
}
return generatePolicy(userId, 'Deny', event.methodArn);
};
在这个示例中,我们在授权过程中使用了一个简单的JavaScript对象来实现缓存。我们首先检查令牌是否已经在缓存中,如果是,我们返回缓存中的策略。否则,我们对令牌进行认证和授权,并在授权成功后将用户ID存储在缓存中。存储在缓存中的信息可以在后续调用中使用,而不必再次进行认证和授权。
在实际生产环境中,您可以使用各种缓存解决方案,如AWS Elasticache或Redis。这些方案都提供更高性能和更可靠的自定义缓存实现。