AWS API Gateway Cognito验证器确实会更改提取的声明中的JWT负载,因为它会添加一些自定义声明来识别验证已完成。如果您不希望这些自定义声明出现在提取的声明中,可以使用Lambda自定义身份验证器来移除它们。
以下是一个示例Lambda自定义身份验证器代码,其中包括移除自定义声明的步骤:
import json
import jwt
def handler(event, context):
# Extract JWT token from request headers
jwt_token = event['headers']['Authorization'].replace('Bearer ', '')
claims = jwt.decode(jwt_token, options={'verify_signature': False})
# Remove custom claims added by API Gateway Cognito authorizer
if 'custom:isAuthenticated' in claims:
del claims['custom:isAuthenticated']
if 'cognito:username' in claims:
del claims['cognito:username']
# Verify JWT signature
# ...
# Return updated claims to API Gateway
policy = generate_policy('user', 'Allow', event['methodArn'], claims)
return policy
在这个示例代码中,请求中的JWT令牌会被解码为一个声明字典,并通过删除custom:isAuthenticated和cognito:username键来删除自定义声明。
随后,可以对JWT签名进行验证,并使用更新后的声明生成策略,以允许或拒绝访问API的请求。
请注意,您需要将此Lambda函数作为自定义身份验证器添加到API Gateway中,并在API的身份验证器设置中使用该函数。