如何用AWS CDK实现API Gateway代理Cognito Token端点并缓存Access Token?
可以用AWS CDK实现Cognito Token缓存的API Gateway方案
完全可以通过AWS CDK实现这个需求——用API Gateway作为Cognito Token端点的中间层,缓存Access Token以减少对Cognito的直接调用。下面是具体的实现思路和代码示例:
核心逻辑
API Gateway作为代理层,接收下游服务的Token请求后:
- 先查询自身的集成缓存,若存在未过期的对应Access Token,直接返回给请求方
- 若缓存中没有有效Token,则转发请求到Cognito的
/oauth2/token端点获取新Token,将Token存入缓存后再返回给下游服务
CDK代码实现(TypeScript)
以下示例基于AWS CDK v2,假设你已有Cognito用户池和客户端(若没有,也可以在CDK中直接创建):
import * as cdk from 'aws-cdk-lib'; import * as apigateway from 'aws-cdk-lib/aws-apigateway'; import * as cognito from 'aws-cdk-lib/aws-cognito'; import { Construct } from 'constructs'; export class CognitoTokenCacheStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // 引用已有的Cognito用户池和客户端(替换为你的实际ID) const userPool = cognito.UserPool.fromUserPoolId(this, 'ExistingUserPool', 'your-user-pool-id'); const userPoolClient = cognito.UserPoolClient.fromUserPoolClientId(this, 'ExistingUserPoolClient', 'your-user-pool-client-id'); // 创建带缓存的API Gateway const tokenCacheApi = new apigateway.RestApi(this, 'CognitoTokenCacheApi', { restApiName: 'Cognito Token Cache Proxy', description: 'Proxy API to cache Cognito Access Tokens', deployOptions: { cachingEnabled: true, cacheClusterSize: '0.5', // 按需选择缓存实例大小,最小为0.5 cacheTtl: cdk.Duration.minutes(15), // 缓存时长需短于Cognito Access Token有效期(默认60分钟) }, }); // 创建对应Cognito Token端点的API资源 const tokenResource = tokenCacheApi.root.addResource('token'); // 配置API Gateway与Cognito Token端点的集成 const cognitoTokenIntegration = new apigateway.HttpIntegration( `https://${userPool.userPoolDomain}.auth.${this.region}.amazoncognito.com/oauth2/token`, { httpMethod: 'POST', options: { // 设置缓存键:根据请求的唯一标识生成,避免不同用户/客户端的Token冲突 cacheKeyParameters: [ 'method.request.querystring.client_id', 'method.request.querystring.username', 'method.request.querystring.scope', ], // 配置请求头与参数转换,适配Cognito的x-www-form-urlencoded格式要求 requestParameters: { 'integration.request.header.Content-Type': "'application/x-www-form-urlencoded'", }, requestTemplates: { 'application/x-www-form-urlencoded': `client_id=$input.params('client_id')&username=$input.params('username')&password=$input.params('password')&grant_type=password&scope=$input.params('scope')`, }, integrationResponses: [ { statusCode: '200', responseTemplates: { 'application/json': '$input.json("$")', }, }, ], }, } ); // 为Token资源添加POST方法,定义必填请求参数 tokenResource.addMethod('POST', cognitoTokenIntegration, { methodResponses: [ { statusCode: '200', responseModels: { 'application/json': apigateway.Model.EMPTY_MODEL, }, }, ], requestParameters: { 'method.request.querystring.client_id': true, 'method.request.querystring.username': true, 'method.request.querystring.password': true, 'method.request.querystring.scope': true, }, }); // 输出API Gateway的访问URL new cdk.CfnOutput(this, 'TokenCacheApiUrl', { value: tokenCacheApi.url, }); } }
关键注意事项
- 缓存TTL设置:Cognito Access Token默认有效期为60分钟,缓存时长必须小于这个值,避免返回过期Token
- 缓存键调整:如果使用
client_credentials授权模式(无用户参与),缓存键需改为client_id和scope,去掉username参数 - 安全控制:务必为API Gateway添加访问权限(如IAM策略、API密钥),防止未授权请求滥用缓存代理
- 缓存失效:若需要主动清除特定缓存条目,可以调用API Gateway的
InvalidateCacheAPI,或者缩短TTL自动失效
内容的提问来源于stack exchange,提问作者undefine97
相关产品推荐
相关产品推荐

