如何将Authorizer Lambda的身份源指定为Cookie?
1. 配置API Gateway授权器的身份源
- 登录AWS控制台,进入API Gateway服务
- 找到目标API,进入授权器页面,创建或编辑已有的Lambda授权器
- 在身份源输入框中填写
method.request.header.Cookie - 注意:API Gateway暂不支持直接指定单个Cookie,会将完整的Cookie字符串传递给Lambda,后续需在Lambda中解析目标Cookie
2. 在Lambda授权器中解析并验证目标Cookie
Lambda需要从传入的事件中提取Cookie字符串,解析出指定的令牌Cookie,再完成验证逻辑。以下是Node.js示例代码:
exports.handler = async (event) => { // 获取请求中的Cookie字符串 const cookieStr = event.headers?.Cookie; if (!cookieStr) { return generatePolicy('unauthorized', 'Deny', event.methodArn); } // 解析Cookie键值对 const cookies = cookieStr.split(';').reduce((acc, cookie) => { const [key, value] = cookie.trim().split('='); acc[key] = value; return acc; }, {}); // 提取目标令牌Cookie(替换成你的Cookie名称) const authToken = cookies['auth-token']; if (!authToken) { return generatePolicy('unauthorized', 'Deny', event.methodArn); } // 这里添加令牌验证逻辑(比如JWT签名校验、有效期检查等) // 示例:假设验证通过 const isValid = true; // 替换为实际验证逻辑 if (!isValid) { return generatePolicy('unauthorized', 'Deny', event.methodArn); } // 验证通过,返回允许访问的策略 return generatePolicy('authorized-user', 'Allow', event.methodArn); }; // 辅助函数:生成IAM策略文档 function generatePolicy(principalId, effect, resource) { return { principalId, policyDocument: { Version: '2012-10-17', Statement: [ { Action: 'execute-api:Invoke', Effect: effect, Resource: resource } ] } }; }
3. 确保API Gateway传递Cookie头(可选)
如果API使用集成请求,需确认Cookie头被正确传递到授权器:
- 进入API Gateway的集成请求配置页
- 在HTTP头部分,添加映射规则:
Cookie->method.request.header.Cookie
4. 客户端设置Secure & HttpOnly Cookie
服务端在返回Cookie时,必须带上Secure和HttpOnly属性,确保令牌无法被前端JS读取,示例响应头:
Set-Cookie: auth-token=your-valid-jwt; Secure; HttpOnly; Path=/; SameSite=Strict
内容的提问来源于stack exchange,提问作者123
相关产品推荐
相关产品推荐

