Select your cookie preferences

We use essential cookies and similar tools that are necessary to provide our site and services. We use performance cookies to collect anonymous statistics, so we can understand how customers use our site and make improvements. Essential cookies cannot be deactivated, but you can choose “Customize” or “Decline” to decline performance cookies.

If you agree, AWS and approved third parties will also use cookies to provide useful site features, remember your preferences, and display relevant content, including relevant advertising. To accept or decline all non-essential cookies, choose “Accept” or “Decline.” To make more detailed choices, choose “Customize.”

Name:
interface
Value:
Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Dec 9, 2024

Override ID token claims

You can use defineAuth and defineFunction to create an Amazon Cognito Pre token generation AWS Lambda trigger to override the token by adding a new claim or modifying the user's group membership.

To get started, install the aws-lambda package, which is used to define the handler type.

Terminal
npm add --save-dev @types/aws-lambda

Create a new directory and a resource file, amplify/auth/pre-token-generation/resource.ts. Then, define the function with defineFunction:

amplify/auth/pre-token-generation/resource.ts
import { defineFunction } from '@aws-amplify/backend';
export const preTokenGeneration = defineFunction({
name: 'pre-token-generation',
resourceGroupName: 'auth'
});

Then, create the corresponding handler file, amplify/auth/post-confirmation/pre-token-generation/handler.ts, file with the following contents:

amplify/auth/pre-token-generation/handler.ts
import type { PreTokenGenerationTriggerHandler } from "aws-lambda";
export const handler: PreTokenGenerationTriggerHandler = async (event) => {
event.response = {
claimsOverrideDetails: {
groupOverrideDetails: {
// This will add the user to the cognito group "amplify_group_1"
groupsToOverride: ["amplify_group_1"],
},
claimsToAddOrOverride: {
// This will add the custom claim "amplfy_attribute" to the id token
amplfy_attribute: "amplify_gen_2",
},
},
};
return event;
};

Lastly, set the newly created function resource on your auth resource:

amplify/auth/resource.ts
import { defineAuth } from '@aws-amplify/backend';
import { preTokenGeneration } from './pre-token-generation/resource';
export const auth = defineAuth({
loginWith: {
email: true,
},
triggers: {
preTokenGeneration
}
});

After deploying the changes, The idToken of the user will be modified as per the trigger above.

{
"cognito:groups": [
"amplify_group_1"
],
"email_verified": true,
"iss": "...",
"cognito:username": "...",
"origin_jti": "...",
"amplfy_attribute": "amplify_gen_2",
"aud": "...",
}