Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement Role Based Access Control using AWS Cognito with Serverless

I created a Serverless Application using AWS Services (S3, Lambda, Cognito, DynamoDB) and the serverless framework with ReactJS by following this tutorial https://serverless-stack.com/. The Tutorial uses AWS Cognito User Pool and Identity Pool for User Management and Authentication Purposes. The application in the tutorial is a "Note-Taking" Application which doesn't have Role Based Access Control within the Application.

However the Application that I am creating requires RBAC and after reading about it, I have understood that RBAC can be implemented either using the "User Groups" or the "Federated Identities". However, I could not still figure out how to properly use either of those in my application.

This is what I have done in the Application till now

  1. Created a User Pool and generated the Pool ID
  2. Added an App Client and generated the App Client ID
  3. Created and deployed my APIs using Serverless
  4. Applied access control to the APIs with Identity Pool using Cognito as the Authentication Provider and Pool Id and App Client Id generated above and then applied a role with the following policy

Policy

{
    "Version": "2012-10-17",
    "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "mobileanalytics:PutEvents",
        "cognito-sync:*",
        "cognito-identity:*"
      ],
      "Resource": [
        "*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:*"
      ],
      "Resource": [
        "arn:aws:s3:::YOUR_S3_UPLOADS_BUCKET_NAME/${cognito-identity.amazonaws.com:sub}*"
      ]
    },
    {
      "Effect": "Allow",
      "Action": [
        "execute-api:Invoke"
      ],
      "Resource": [
        "arn:aws:execute-api:YOUR_API_GATEWAY_REGION:*:YOUR_API_GATEWAY_ID/*"
      ]
    }
  ]
}

This allows everyone to access all the APIs. How do I assign role to each user and then restrict the access to certain APIs based on their Role?

like image 407
Shashank Avatar asked Sep 19 '17 07:09

Shashank


1 Answers

There's a few ways to do it; more to the point, you don't need an identity pool at all.

  • Inside a Cognito user pool, each group you define may have an IAM role associated with it. Users who authenticate will assume that role (if they have multiple groups, then it uses precedence order)
  • Alternatively if all you need to do is authorisation on an API gateway (instead of a full IAM setup), then a custom authorizer lambda attached to the gateway will be able to do both authentication against Cognito, and then authorisation based on the authenticated user's details.
like image 110
Trent Bartlem Avatar answered Oct 07 '22 21:10

Trent Bartlem