You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Cognito用户信息传递至HTTP集成?

完全可行,以下是两种常用实现方案

方案一:通过API Gateway直接转发Cognito用户信息

API Gateway完成Cognito用户池的令牌校验后,可通过集成请求映射模板将认证后的用户声明(claims)直接转发到Express应用,无需Express再做令牌解析。

  1. 配置API Gateway映射模板
    在API Gateway对应资源的集成请求中,设置映射模板(Content-Type选择application/json),将Cognito返回的用户声明注入请求头或请求体:
{
  "headers": {
    "X-User-Sub": "$context.authorizer.claims.sub",
    "X-User-Email": "$context.authorizer.claims.email",
    "X-User-Claims": "$util.base64Encode($context.authorizer.claims)"
  }
}

$context.authorizer.claims包含Cognito返回的所有用户信息,比如用户唯一ID(sub)、邮箱、用户名等。

  1. 在Express中读取用户信息
    直接从请求头中获取转发的用户数据:
app.get('/protected', (req, res) => {
  const userId = req.headers['x-user-sub'];
  const userEmail = req.headers['x-user-email'];
  // 解码完整用户声明
  const userClaims = JSON.parse(Buffer.from(req.headers['x-user-claims'], 'base64').toString());
  res.json({ userId, userEmail, fullClaims: userClaims });
});

方案二:Express自行验证并解析JWT令牌

如果需要Express直接处理令牌验证逻辑,API Gateway只需校验令牌有效性,再将原始JWT令牌转发给Express,由Express自行解析用户信息。

  1. 配置API Gateway转发令牌
    在集成请求的映射模板中,将请求头中的Authorization令牌转发到Express:
{
  "headers": {
    "X-Auth-Token": "$input.params('Authorization')"
  }
}
  1. 在Express中验证并解析令牌
    使用jsonwebtoken结合Cognito公钥验证令牌,解析用户信息:
const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');

// 初始化JWKS客户端,获取Cognito公钥
const client = jwksClient({
  jwksUri: 'https://cognito-idp.<region>.amazonaws.com/<user-pool-id>/.well-known/jwks.json'
});

function getKey(header, callback) {
  client.getSigningKey(header.kid, function(err, key) {
    const signingKey = key.getPublicKey();
    callback(null, signingKey);
  });
}

app.get('/protected', (req, res) => {
  const token = req.headers['x-auth-token'].split(' ')[1]; // 移除Bearer前缀
  jwt.verify(token, getKey, { audience: '<client-id>', issuer: 'https://cognito-idp.<region>.amazonaws.com/<user-pool-id>' }, (err, decoded) => {
    if (err) return res.status(401).send('Invalid token');
    // decoded中包含完整用户信息
    res.json({ user: decoded });
  });
});

注意替换代码中的<region>、<user-pool-id>、<client-id>为你的实际配置。

两种方案都能让Express获取到Cognito用户信息:方案一更简便,无需Express处理令牌验证;方案二更灵活,适合需要在Express侧做额外校验逻辑的场景。

内容的提问来源于stack exchange,提问作者jackie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:20:24