HowTo: Grant IAM role to Cognito authenticated user

Previously (here), we talked about how to authenticate a user with Cognito User Pool.

After user is authenticated, they may want to access their own resources (e.g. S3 object). One way is to grant an IAM role to our application to be able to access resources of all users. The other way is to grant an IAM role which can access the resource only belonging to that user. We will work on the second way.

We need to user Cognito Identity Pool to grant the IAM role.

Setup Cognito

We need to create the identity pool. We name it . Our identity pool needs to link up with our user pool and user pool client. If you follow the previous article, you should have values for , , .

We need to prepare the trust policy. Create a file called . Please replace with the value we just get in previous step. This role can only be assumed by the identity pool we just created and it is for authenticated user only.

We create our role. We call it .

We need to attach the permission policy to our newly created role. In this example, we will grant the access right to S3 service. User can only access to their own S3 folder. They cannot access other people’s folder. Create a file called . Please replace with your bucket name.

We attach the policy to our role.

Finally, we need to set the role to our identity pool.

Logic flow

  1. We get the ID token if user is authenticated.
  2. With the ID token, we can get user’s identity ID.
  3. With the identity ID, we can get the credential.
  4. We can use the credential to call S3 service on behalf of that user.

Get ID token

In our previous article, we call to login. We can get the ID token from the response.

If you reuse the function we created in our previous article, then it should be like this.

Get identity ID

We need to call to get the identity ID.

Get credential

It is straightforward to get the credential.

Combining the last 2 pieces of code together, we get this.

Call S3 service

We can now call the S3 service. The following piece of code will create a new file .

Remember we have in our ? I thought that was the property in our ID Token. But actually that refers to identity ID. I kept having when I worked on that. Much time is wasted.

Combing other code together.

Software Engineer