Search code examples
amazon-web-servicesaws-lambdaamazon-cognitoamazon-rds

Implement AWS Cognito authorization to control RDS mysql records


In my react application, once a valid user logs-in to my app, he will be redirected to the dashboard where he can see all the products. If there are 10 products available in AWS-RDS-Mysql-Table called Products-Table, he will see all 10 products.

For this, I'll make a backend API endpoint /products call and it get gets me all products by running a simple sql query : SELECT * FROM Products-Table.

So far so good.


My Current AWS pipeline basic flow: **`ReactApp => (api request comes to) HTTP API gateway => LAMBDA (nodejs) => RDS (mysql)`**

I also have Cognito user pool + Lambda authorizer. I have setup a basic authentication flow using lambda authorizer to check if request is valid or not. All this is working fine.

My Cognito groups & Users.

eg.

AdminGroup:
               User1
               User2

WorkersGroup:
               User3
               User4

Currently it doesn't matter If I login with AdminGroup's users or WorkersGroup's users. Every time I see 10 products.

Is the below scenario possible using cognito and AWS IAM roles/policies concept ?

When I login with AdminGroup's users, I should be able to see all the products.
BUT
When I login with WorkersGroup's users, I should be able to see ONLY 5 product (Let's say)


Solution

  • Cognito is providing application level security and does not filter queries, as it doesn't know how. Specifically, Cognito can't answer the question on how to filter Products-Table to the user and/or user group. This has to be implemented in software, meaning in the LAMBDA (nodejs) part of your application.

    AWS has documentation an this: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-enable-cognito-user-pool.html among other solutions. In short:

    1. Configure Cognito User Groups
    2. Configure API Gateway to use Cognito Lambda Authorizer
    3. Configure API Gateway to provide the information to Lambda ("claims")
    4. Program the LAMBDA (nodejs) to retrieve this information and adjust the query as needed for the user/group

    I think you have done 1 + 2 already, but are missing 3+4.