Problem to migrate rules to action

Hello, we currently run the following rule and are now trying to convert it into an action since rules will be discontinued.

function (user, context, callback) {
  const namespace = 'https://example.com';
  const assignedRoles = (context.authorization || {}).roles;

  let idTokenClaims = context.idToken || {};
  let accessTokenClaims = context.accessToken || {};
  
  if (idTokenClaims[`${namespace}/roles`] && accessTokenClaims[`${namespace}/roles`]) {
  	return callback(null, user, context);
	}

  idTokenClaims[`${namespace}/roles`] = assignedRoles;
  accessTokenClaims[`${namespace}/roles`] = assignedRoles;

  context.idToken = idTokenClaims;
  context.accessToken = accessTokenClaims;

  callback(null, user, context);
}

Basically, before adding a claim, we perform a check to ensure that it doesn’t already exist.

  if (idTokenClaims[`${namespace}/roles`] && accessTokenClaims[`${namespace}/roles`]) {
  	return callback(null, user, context);
}

When trying to convert this to an action, I noticed that there isn’t a clear way to check if that permission already exists. For example, neither the event nor the api parameter of an action shows if it exists or not. I would like to know from you what to do?

Hi @g.felippe5965,

I understand you are trying to migrate your existing Rules to Actions.

This check is unnecessary because a namespaced claim can only be appended to the tokens after the authentication flow has completed.

Therefore, to simplify your code and use Actions, I have attached the converted code snippet below:

exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://myapp.example.com';
  if (event.authorization) {
    // Set claims in ID token
    api.idToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
    // Set claims in access token
    api.accessToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
  }
};

(Reference: Adding custom claims to tokens)

Cheers,
Rueben

2 Likes

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