Hello, I was trying to implement M2M access token caching using the instructions provided in this post:
In this example the token caching is done as a post login step, however for M2M caching I tried to implement inside the onExecuteCredentialsExchange, but when I tried out the code it got stuck in a loop and I quickly exceeded my monthly quota. I think the loop happens when I try to call the authClient.oauth.clientCredentialsGrant() function because it automatically counts as an on execute credentials exchange step which calls the action again and causes a loop. The code I used is the following:
exports.onExecuteCredentialsExchange = async (event, api) => {
console.log("I am inside the Token Caching Action.");
const AuthenticationClient = require('auth0').AuthenticationClient;
const jwt_decode = require('jwt-decode');
const record = api.cache.get('management-token');
console.log("Record: ", record);
let token = record?.value;
let current_time = Date.now().valueOf() / 1000;
console.log("Cached token: ", token);
if (token != undefined) {
var decoded = jwt_decode(token);
}
if (token != undefined && decoded.exp > current_time) {
const managementWithOldToken = new AuthenticationClient({
token: token,
domain: event.secrets.domain,
});
} else if (token == undefined || decoded.exp < current_time) {
const management = new AuthenticationClient({
domain: event.secrets.domain,
clientId: event.secrets.clientId,
clientSecret: event.secrets.clientSecret,
tokenProvider: {
enableCache: true,
cacheTTLInSeconds: 86400
}
});
const newToken = await management.oauth.clientCredentialsGrant({
audience: event.secrets.audience,
});
console.log("New token is: ", JSON.stringify(newToken));
const result = api.cache.set('management-token', JSON.stringify(newToken));
console.log("Token is cached.");
if (result.type === 'error') {
console.log("failed to set the token in the cache with error code ", result.code);
} else {
console.log("successfully set access token in cache");
}
const managementWithNewToken = new AuthenticationClient({
token: newToken,
domain: event.secrets.domain,
});
const check = api.cache.get('management-token');
console.log("Check: ", check);
}
};
I have a few questions regarding the M2M token caching in Actions:
- Is the access token created in the Action is the same token that is issued to the application performing the Client Credentials flow?
- When caching anything it says that the cache can persist upto 15 minutes, however when I re-run my the flow the cache is always empty and returns a undefined value, the only time when I can access the cache is during the execution of the action or from another action, but in the same execution flow. So, my question is does the cache only work within the same flow?