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

Page updated Apr 29, 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',
});

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": "...",
}