[英]API Gateway Authorizer - IAM policy not caching
我正在嘗試緩存授權方 lambda 首次驗證 JWT 令牌時返回的 IAM 策略。 我已在 API 網關授權器中啟用並將authorizerResultTtlInSeconds
設置為3500
秒。 但是,我仍然看到在緩存時間范圍內向授權方 lambda function 發送請求。
我的 node.js 腳本如下:
const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');
const keyClient = jwksClient({
jwksUri: process.env.JWKS_URI
})
const allow = {
"principalId": "user",
"policyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "execute-api:Invoke",
"Effect": "Allow",
"Resource": process.env.RESOURCE // RESOURCE = *
}
]
}
}
const unauthorized = {
"error": "Unauthorized",
}
//excluded verificationJWTOptions object and getSigningKey function for simplicity
function validateJWTToken(token, callback) {
jwt.verify(token, getSigningKey, verificationJWTOptions, (error) => {
if (error) {
callback(unauthorized)
} else {
callback(null, allow)
}
})
}
exports.handler = (event, context, callback) => {
const token = extractTokenFromHeader(event);
validateJWTToken(token, callback);
}
不知道我錯過了什么。 任何幫助將非常感激!
我發現我沒有正確測試 API Gateway Authorizer 緩存邏輯。 我一直在測試各種場景,在這里發現了兩種情況:
當令牌有效時:當調用endpoint
,請求會轉到驗證/使令牌無效的 Lambda 授權方。 IAM 策略由函數返回給 API Gateway Authorizer 並被緩存(在這種情況下 - 58 minutes, 20 seconds
)。
Token Source
指定的頭部名稱成為緩存鍵,授權方生成的授權策略成為緩存值。 API 網關將檢查Token Source
指定的標頭。 如果 header 的值與 key 匹配,API Gateway 將不會調用 Lambda Authorizer 而是根據配置的TTL
檢查策略是否有效。
如果在緩存時間范圍內生成了新令牌,則會再次調用 Lambda 授權程序並緩存此令牌。 因此,如果使用這兩個令牌調用終端節點,則不會調用 Lambda 授權程序,因為這些令牌的 IAM 策略已經在給定的緩存時間范圍內緩存,並且響應會被返回。
當令牌無效時:例如,如果令牌在11:00:00AM
到11:30:00AM
30 minutes
有效,並且緩存TTL
設置為58 minutes
。 客戶端使用該令牌發出 2 個 API 請求,一個在11:29:59AM
和另一個在11:31:3APM
- 然后這兩個請求都將被接受,盡管第二個請求使用了過期的令牌。 這基本上意味着JWT token
被緩存TTL
擴展。
我使用 AWS CDK 遇到了同樣的問題。 我相信這是 CDK、CloudFormation 或 API 網關本身的錯誤。
解決方法是手動重新部署 API 網關階段。 否則緩存選項無效。
可以從“資源”部分的“操作”菜單中找到部署操作:
我認為這是一個錯誤,因為 AWS CDK 應該默認自動執行此操作,因為deploy: true
是RestApi
構造中的默認值:
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_apigateway.RestApi.html#deploy
指示是否應為此 API 自動創建 Deployment,並在 API model(資源、方法)更改時重新創建。
在 CDK 代碼中,我能夠通過重命名RequestAuthorizer
id 來強制重新部署:
api.root
.addResource("things")
.addMethod("POST", new LambdaIntegration(nextHandler, {}), {
apiKeyRequired: true,
authorizer: new RequestAuthorizer(
this,
"Authorizer3", // 👈 Update this if you change resultsCacheTtl
{
// WARNING: resultsCacheTtl change requires manual
// deployment from the AWS console. Or update the
// RequestAuthorizer id
resultsCacheTtl: Duration.minutes(5),
handler: authorizer,
identitySources: [IdentitySource.queryString("jwt")],
},
),
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.