Enrich user token with additional claims
In this activity, we will enrich users token with additional claims using Pre Token Generation lambda trigger. This trigger will add “department” claim to the token as users sign-in. In real-world scenario, this could be based on a backend check to verify user’s department or it could be a custom claim in user’s profile that can be only modified by administrator.
- Navigate to the Lambda console and click on the Create Function button. Select Author from scratch and give the lambda function a name. Select Node.js runtime.
- In the lambda window, click on the index.js to select it and replace the code with the following code. Click on Deploy when done.
exports.handler = (event, context, callback) => {
event.response = {
claimsOverrideDetails: {
claimsToAddOrOverride: {
department: 'Engineering',
},
},
};
callback(null, event);
};
- Navigate back to the Cognito console, select your user pool, select the triggers menu item. Scroll down to the Pre Token Generation section, click on the dropdown and select the lambda you just created. Click on the Save Changes button.
- Go back to jsfiddler and check that the new claims are coming in user’s idtoken. Note that the pretoken generation trigger does not work on access tokens.