Run Auth0 Rules as Post-Login Actions

I built an npm package that can run old Auth0 Rules as a Post-Login Actions, and wanted to share it here.

How it works

  • Derives old user and context objects from the event object
  • Runs the rule, which mutates the context object
  • Makes api calls based on changes to the context object

Example

Add as dependency to a Post Login action

auth0-rule-as-action@latest

Example Post Login action

const RuleToAction = require("auth0-rule-as-action");

/**
 * The Rule
 */
function exampleRule(user, context, callback) {
  context.idToken["https://example.com/test"] = "testValue";
  
  if (context.clientName === "All Applications") {
    const date = new Date();
    const d = date.getDay();

    if (d === 0 || d === 6) {
      return callback(
        new UnauthorizedError("This app is available during the week"),
      );
    }
  }

  callback(null, user, context);
}

/**
 * Handler that will be called during the execution of a PostLogin flow.
 *
 * @param {Event} event - Details about the user and the context in which they are logging in.
 * @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login.
 */
exports.onExecutePostLogin = async (event, api) => {
  const rule = exampleRule;
  // Instantiate a Rule to Action converter
  const converter = new RuleToAction(api);
  // Run the Rule as an Action
  await converter.convert(event, rule);
};

The library runs this rule, and under the hood calls

api.idToken.setCustomClaim("https://example.com/test", "testValue");

And if it’s the weekend,

api.access.deny("This app is available during the week")
1 Like

Hi @epicpatka,

Thank you for sharing your project with the Auth0 Community!

This is a very clever and interesting approach to bridging the gap between legacy Rules and the modern Actions framework. We appreciate you taking the time to build this tool and write up a clear explanation for other community members.

While your library is an innovative solution for compatibility, our official and strongly recommended path is for users to migrate their legacy Rules to native Post-Login Actions. This ensures long-term stability, security, and access to the full capabilities of the Actions framework.

For detailed instructions and code examples, please see our official migration guide:
https://auth0.com/docs/customize/actions/migrate/migrate-from-rules-to-actions

Thank you again for your contribution. We love seeing the creative solutions developers in our community come up with!

If you have any other questions, feel free to reach out.

Have a good one,
Vlad

1 Like