Convert Rule into Action that converts user profile metadata upon request

Hello!
I have a Rule that converts user profiles metadata when fetching user data.
At least that is what I believe the rule does.
I have tried - but do not understand how to convert this to an Action.

My main questions are:

  1. What is the equivalent to context.idToken['${namespace}/usertype]
  2. Is a callback still needed? callback(null, user, context);
  3. What is the appropriate trigger for this?

My previous rule:
“Add metadata to user profile”

function(user, context, callback) {
  user.app_metadata = user.app_metadata || {};
  const namespace = 'https://my.metadata.com';
  if(user.app_metadata.usertype) {
    context.idToken[`${namespace}/usertype`] = user.app_metadata.usertype;
  }
  if(user.app_metadata.coops) {
    context.idToken[`${namespace}/coops`] = user.app_metadata.coops;
  }  
  if(user.app_metadata.coopnames) {
    context.idToken[`${namespace}/coopnames`] = user.app_metadata.coopnames;
  }   
  callback(null, user, context);
}

Hi @kazuyuki,

Welcome to the Auth0 Community!

I understand that you have some questions about converting your existing Rule to an Action.

First, allow me to address your questions:

  1. To achieve the same functionality as context.idToken['${namespace}/usertype'], you can use the following command in your Action script: api.idToken.setCustomClaim(${namespace}/usertype, VALUE).

For additional information and guidance, you can refer to this FAQ: Adding custom claims to tokens

  1. The good news is that the callback is no longer required. You can safely omit it.

  2. For your scenario, the appropriate trigger is the Post-Login Action flow. Just a friendly reminder, Rules execute post-login.

To make things even more convenient for you, I have rewritten your Rule as an Action. Here’s the updated code snippet:

exports.onExecutePostLogin = async (event, api) => {

  const namespace = 'https://my.metadata.com';
  if(event.user.app_metadata.usertype) {
    api.idToken.setCustomClaim(${namespace}/usertype, eventuser.app_metadata.usertype);
  }
  if(event.user.app_metadata.coops) {
    api.idToken.setCustomClaim(${namespace}/coops, event.user.app_metadata.coops);
  }  
  if(event.user.app_metadata.coopnames) {
    api.idToken.setCustomClaim(${namespace}/coopnames, event.user.app_metadata.coopnames);
  }   
}

Please don’t hesitate to reach out if you have any further questions.

Thanks,
Rueben

2 Likes

Wow! Thank you very much for the prompt reply and help with converting the code!
\(^__^)/

I had forgotten that rules are post login blush
It all made sense when I looked at the Login flow though.
The code works perfectly!

Kind regards
Kazuyuki

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.