This https://stackoverflow.com/a/58686493/4752223答案让我走上了一条简单的道路,但我意识到还有一条更容易的道路。
如果您像这样转储 Lambda(python 代码)收到的内容。
然后像这样调用 API(GET/POST/其他取决于您如何定义 API)
# curl --request GET --header "Authorization: ${TOKEN}" "${GATEWAY_URL}"
你会得到一堆文字。将其粘贴到https://jsonformatter.curiousconcept.com/ https://jsonformatter.curiousconcept.com/很好地格式化它,你会发现在事件中你有很多信息,比如
{
"version":"2.0",
"routeKey":"ANY /*****",
"rawPath":"/default/****",
"rawQueryString":"",
"headers":{
"accept":"*/*",
"authorization":"eyJraW...QiOi",
"content-length":"0",
"host":"*******.execute-api.eu-west-1.amazonaws.com",
"user-agent":"curl/7.52.1",
"x-amzn-trace-id":"Root=1-5ff1***eee7347",
"x-forwarded-for":"**.**.243.124",
"x-forwarded-port":"443",
"x-forwarded-proto":"https"
},
"requestContext":{
"accountId":"****",
"apiId":"*****",
"authorizer":{
"jwt":{
"claims":{
"at_hash":"-pO***Eg",
"aud":"1jk***0n0",
"auth_time":"160***928",
"cognito:username":"357d***a77de4d",
"email":"***@gmail.com",
"email_verified":"true",
"event_id":"19f7e***dc0e80",
"exp":"16***28",
"iat":"16***928",
"iss":"https://cognito-idp.eu-west-1.amazonaws.com/eu-west-1_***8z",
"name":"UserName",
"sub":"357***77de4d",
"token_use":"id"
},
"scopes":"None"
}
},
"domainName":"***.execute-api.eu-west-1.amazonaws.com",
"domainPrefix":"***",
"http":{
"method":"GET",
"path":"/default/***",
"protocol":"HTTP/1.1",
"sourceIp":"***",
"userAgent":"curl/7.52.1"
},
"requestId":"Yi***sA=",
"routeKey":"ANY /***",
"stage":"default",
"time":"02/Jan/2021:23:45:15 +0000",
"timeEpoch":1609631115197
},
"isBase64Encoded":false
}
也就是说,所有用户详细信息都在那里,您无需执行任何操作即可获取它们。
特别是,这 2 个在这里
event["requestContext"]["authorizer"]["jwt"]["claims"]["email"]
event["requestContext"]["authorizer"]["jwt"]["claims"]["name"]
这具有更好的含义。
您可以利用 HTTP API Gateway + Lambda 来:
- 验证访问令牌(如果无效或过期,您将收到“未经授权”响应)
- 提取令牌范围/详细信息
所有这一切都在 130 毫秒内完成(您只需支付 3 毫秒的费用)。无需加载库,无需操作数据,无需手动解码,没有废话。
唯一需要的工作是配置用户池和 API 网关(HTTP 或 REST 类型)来为您进行身份验证。
如果您想知道从哪里获取 TOKEN 的值,它会在成功登录 Cognito 后调用的 URL 上进行编码。
请注意,您可能会在响应 URL 中获取 2 个令牌:ID_TOKEN 和 ACCESS_TOKEN。要获取用户详细信息,您需要使用 ID_TOKEN 调用 API。