Skip to content

Issues with Including Custom Attributes in Cognito Access Tokens Using Pre Token Generation Lambda

1

I am trying to include custom attributes in the access tokens generated by AWS Cognito using a Pre Token Generation Lambda trigger. Despite setting up the Lambda and updating the user pool client settings, the custom attributes are not appearing in the access token.

Here is my lambda code and my configuration of my app client

export const handler = async (event) => {

const userAttributes = event.request.userAttributes;

event.response = {
    claimsOverrideDetails: {
        claimsToAddOrOverride: {
            "custom:custom:attribute1": userAttributes["custom:custom:attribute1"]
        }
    }
};

return event; };

Enter image description here **I'm using v1 event version for Pre Token Generation Lambda trigger. **** Still I'm not getting any custom attributes in access token

1 Answer
0

Greeting

Hi Pavin,

Thank you for reaching out with your question about including custom attributes in AWS Cognito access tokens using a Pre Token Generation Lambda trigger. It sounds like you've put considerable effort into configuring both your Lambda function and user pool client settings, but you're still running into issues where the custom attributes don't appear in the access token. Let’s work through this together! 😊


Clarifying the Issue

From what you've described, you’re attempting to add custom attributes to access tokens using a Pre Token Generation Lambda trigger in Cognito. You’ve already updated your Lambda function to manipulate token claims via the claimsOverrideDetails field, and your user pool client settings appear to allow the necessary authentication flows. However, despite these steps, the expected custom attributes aren't being added to the token.


Why This Matters

Custom attributes in tokens enable downstream services to make decisions based on user-specific data, such as roles, preferences, or subscription tiers. Without these attributes, applications might lose critical context about the user, leading to limited functionality or reduced personalization.


Key Terms

  • Pre Token Generation Lambda Trigger: A Lambda function invoked by AWS Cognito during token generation, allowing customization of token claims.
  • Custom Attributes: User-defined attributes added to a Cognito user pool schema for storing additional user information.
  • App Client Settings: Configuration settings for a Cognito user pool client, controlling authentication flows and attribute read/write permissions.
  • claimsOverrideDetails: A parameter in the Lambda trigger response for adding or overriding token claims.
  • JWT (JSON Web Token): The format of the access token, containing a payload that includes claims about the user.

The Solution (Our Recipe)

Steps at a Glance:

  1. Validate the custom attribute schema in Cognito.
  2. Ensure the app client settings allow read access for the custom attribute.
  3. Debug the Lambda function to confirm the custom attribute is available.
  4. Update the Lambda function to correctly manipulate token claims.
  5. Test the changes using AWS CLI and Postman.
  6. Decode the token to verify the custom attribute has been added.
  7. Optionally, test with Cognito Hosted UI for a simpler validation process.

Step-by-Step Guide:

  1. Validate the Custom Attribute Schema in Cognito
    • In the Cognito user pool, verify that the custom attribute (e.g., custom:custom_attribute1) has been added to the schema and is active.
    • Ensure the attribute name matches exactly what you’re referencing in the Lambda function.

  1. Ensure App Client Settings Allow Read Access
    • In the Cognito console, navigate to the user pool's "App clients" section.
    • Select the app client and click on “Show details” for “Set attribute read and write permissions.”
    • Confirm that the custom attribute is enabled for "read" access.

  1. Debug the Lambda Function
    • Add logging to your Lambda function to inspect the event.request.userAttributes object. For example:
      console.log("User Attributes:", JSON.stringify(event.request.userAttributes));
    • Deploy the updated Lambda function and test the output in CloudWatch Logs to ensure the custom attribute is present.

  1. Update the Lambda Function
    • Modify your Lambda function to include the custom attribute in the token. Here’s an example:
      exports.handler = async (event) => {
          console.log("User Attributes:", JSON.stringify(event.request.userAttributes));
          
          const userAttributes = event.request.userAttributes;
          
          // Add custom attribute to token claims
          event.response = {
              claimsOverrideDetails: {
                  claimsToAddOrOverride: {
                      "custom:custom_attribute1": userAttributes["custom:custom_attribute1"]
                  }
              }
          };
          
          return event;
      };

  1. Test the Changes Using AWS CLI and Postman
    • Use AWS CLI to initiate an authentication flow and retrieve a token:
      aws cognito-idp initiate-auth \
          --client-id <app_client_id> \
          --auth-flow USER_PASSWORD_AUTH \
          --auth-parameters USERNAME=<username>,PASSWORD=<password>
    • Alternatively, use Postman to authenticate against Cognito and retrieve the access token.

  1. Decode the Token to Verify the Custom Attribute
    • Use a tool like jwt.io to decode the access token. You should see the custom attribute included in the token payload. For example:
      {
          "sub": "1234567890",
          "email": "source_at_email.com",
          "custom:custom_attribute1": "example_value"
      }

  1. Optionally, Test with Cognito Hosted UI
    • Use the Cognito Hosted UI to simulate login flows and retrieve tokens directly from the browser. This can simplify the testing process and ensure your app client and user pool configurations are working as expected.

Closing Thoughts

You’ve taken an important step by configuring a Pre Token Generation Lambda trigger for your user pool. By validating the schema, ensuring app client settings are correct, debugging the Lambda function, and testing with tools like AWS CLI, Postman, and Cognito Hosted UI, you should be able to resolve this issue and see your custom attributes in the access token.

Adding custom attributes to tokens has several real-world applications, including:

  • User Roles: Including roles like "admin" or "editor" in the token to control access to specific features.
  • Subscription Tiers: Adding attributes like "premium" or "basic" to customize user experiences in downstream applications.
  • Preferences: Storing user-specific settings, like preferred language or theme, for personalized services.

For additional resources, check out:


Farewell

I hope this helps, Pavin! Let me know if you have any further questions or run into additional issues—I’d be happy to assist. Good luck, and happy coding! 🚀😊


Cheers,

Aaron 😊

answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.