Last Updated: Sep 27, 2024
Overview
This article explains how to call an external API to retrieve a response and set the API response as a custom claim in the Access/ID Token for an application.
Applies To
- Actions
- Custom Claims
Solution
To append the data from an external API response as a custom claim, use a Post-Login Action script.
See below for an example using an Axios POST request:
exports.onExecutePostLogin = async (event, api) => {
const axios = require('axios');
const namespace = 'https://myapp-example.com';;
const url = 'https://YOUR_URL';;
const options = {
headers: {
'Content-Type': 'application/json'
}
};
const data = {
username: event.user.username,
email: event.user.email
};
var response = await axios.post(url, data, options);
console.log(response.data);
if (event.authorization) {
api.idToken.setCustomClaim(`${namespace}/CUSTOM_CLAIM_NAME_HERE`, response.data);
api.accessToken.setCustomClaim(`${namespace}/CUSTOM_CLAIM_NAME_HERE`, response.data);
}
};
NOTE: It is needed to save the response as a variable and await for the Axios post result before storing it as a custom claim in the token. Not waiting for the response would result in undefined custom claims or claims that do not get appended to the token. This happens because Auth0 actions batch requests after the Action exits.