在 AWS Cognito 中,API Usage Plan 的使用需要使用 API Key 进行身份认证。但是,当用户使用 API Key 时,有时会出现延迟加载问题。为了解决这个问题,可以采取以下措施:
在 AWS Cognito 中,可以设置 API Key 的延迟加载模式。这意味着当用户使用 API Key 时,它不会立即生效,而是需要一定的时间(通常为几秒钟)才能生效。这种方式可以避免 API Key 在未授权的情况下被滥用。
代码示例:
const AWS = require('aws-sdk');
const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
// 延迟加载 API Key
const params = {
UserPoolId: 'USER_POOL_ID',
Username: 'USERNAME',
DelayUntil: 10 // 延迟10秒钟加载 API Key
};
cognitoidentityserviceprovider.adminCreateUserAuth(params, function(err, data) {
if (err) console.log(err, err.stack); // error occurred
else console.log(data); // successful response
});
如果您的应用程序使用的是大量的 API Key,那么您可以优化 API Key 生成方式来避免延迟加载问题。例如,您可以使用 AWS Lambda 函数来生成 API Key,或者使用 AWS API Gateway 的自定义身份验证功能来进行身份认证。
代码示例:
// 使用 AWS Lambda 函数生成 API Key
exports.handler = async function(event, context) {
const params = {
name: 'API_KEY_NAME',
customerId: 'CUSTOMER_ID'
};
const key = await generateApiKey(params);
return key;
}
function generateApiKey(params) {
const apigateway = new AWS.APIGateway();
return new Promise((resolve, reject) => {
ap