Reputation: 85
I have an API Gateway HTTP API. For some of the routes I've attached a Cognito User Pool authorizer which works fine. However now I want to add a restriction to the authorization so that only the user with the correct username can access a certain API.
For example, if the route is PUT /users/{username}
, I only want the user with the corresponding username to be able to edit his/her profile information. For other users, it should be unauthorized.
This seems like a common use case, how do I do this? I've looked into scopes but that doesn't seem to be the solution. Would I have to write a custom Lambda authorizer for this, instead of using the Cognito authorizer? If so could you provide an example, since I have no experience writing the Lambda authorizer.
Upvotes: 1
Views: 741
Reputation: 36
You can use a Mapping Template to structure a request in API Gateway, and use the information stored in a Cognito token from there https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference.
For your specific request to /users/{username}
, you could use an if to only provide the desired information if the user matches How to use IF condition in AWS Api gateway mapping templates. can i use if condition without using foreach?.
Alternatively, you may be able to simplify the path to PUT to /users, then pull the username from the cognito token and use it in the mapping template How can I access the Cognito username of the caller in a Lamda function?.
Upvotes: 2