user1868744
user1868744

Reputation: 1033

Add custom roles to AWS Cognito User Pool Access Token

I am using AWS Cognito User Pool to secure my web app, mobile app and APIs. I have a database with roles and permissions defined. I would like to add "roles" to Access Token during login process so that I do not need to make a database call to check for user roles.

I will not be able to use Cognito custom attributes because people can create custom roles from the front end and all of this information is saved in a database.

Upvotes: 2

Views: 1621

Answers (1)

Gary Archer
Gary Archer

Reputation: 29301

Cognito added support for Access Token Customization in 2023. You have to activate Advanced Features and can then control claims issued. The usual OAuth pattern is to consider scopes to contain claims and only issue claims when the scope is present. My blog post has some further info on the steps.

export const handler = function(event, context) {
  
  const response = {
    claimsAndScopeOverrideDetails: {
      idTokenGeneration: {
        claimsToSuppress: []
      },
      accessTokenGeneration: {
        claimsToAddOrOverride: {}
      }
    }
  };
  
  if (event.request.scopes.indexOf('myscope') !== -1) {
    const customClaims = response.claimsAndScopeOverrideDetails.accessTokenGeneration.claimsToAddOrOverride;
    customClaims.role = event.request.userAttributes['custom:role'];
  }

  event.response = response;
  context.done(null, event);
};

Before this was supported I used an alternative pattern of looking up extra claims in the API code and caching them in the API against a hash of the access token. There are still often valid reasons to do this, if you don't want to store some user attributes in Cognito.

Upvotes: 6

Related Questions