AWS Cognito + API网关,基于用户名进行授权

问题描述

我有一个API网关HTTP API。对于某些路由,我附加了一个运行良好的Cognito用户池授权者。但是,现在我想对授权添加限制,以便只有具有正确用户名用户才能访问特定的API。

例如,如果路由为PUT /users/{username},我只希望具有相应用户名用户能够编辑其个人资料信息。对于其他用户,应该未经授权。

这似乎是一个普通的用例,我该怎么做?我研究了范围,但这似乎不是解决方案。我是否需要为此编写自定义Lambda授权者,而不是使用Cognito授权者?如果可以的话,您可以提供一个例子,因为我没有编写Lambda授权器的经验。

解决方法

您可以使用映射模板在API网关中构建请求,并从https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference处使用存储在Cognito令牌中的信息。

对于您对/users/{username}的特定请求,可以使用if来仅在用户匹配How to use IF condition in AWS Api gateway mapping templates. can i use if condition without using foreach?时提供所需的信息。

或者,您可以简化到/ users的PUT路径,然后从Cognito令牌中提取用户名并在映射模板How can I access the Cognito username of the caller in a Lamda function?中使用它。