# Fine-grained Access with AssumeRole

So far what we have seen is kind of a static assignment of the roles and using the services accordingly. When we run our code inside Lambda, it has its own role and permissions.

* API Gateway Authorizer to validate that we have a valid Cognito session
* API Gateway Scope to validate that the user has the permission to invoke the API
* **But how we do make sure that the Lambda function has the exact permissions as per the request role?**

In that case, we will be using Fine-grained access control. Conceptually it is a very simple practice that is used by most of the AWS services.&#x20;

We will be using the AssumeRole API inside the Lambda function based on the incoming Cognito profile detail.&#x20;

{% hint style="danger" %}
In this context, the executing Lambda by default has only the AssumeRole permission so that it can transition to the new role. The target role must have all the policies to execute the function's logic correctly.
{% endhint %}

```
const AWS = require('aws-sdk');
const sts = new AWS.STS();

sts.assumeRole({
  RoleArn: '<role arn>',
  RoleSessionName: 'MySession'
}, (err, data) => {
  if (err) { // an error occurred
    console.log('Cannot assume role');
    console.log(err, err.stack);
  } else { // successful response
  
    // This is important as AssumeRole will not automatically update the existing Lambda role
    AWS.config.update({
      accessKeyId: data.Credentials.AccessKeyId,
      secretAccessKey: data.Credentials.SecretAccessKey,
      sessionToken: data.Credentials.SessionToken
    });
  }
});
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dhavaln.gitbook.io/serverless-docs/serverless-apis/fine-grained-access.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
