Enforcing Conditional MFA in Auth0 Using Actions: Complete Guide with Code
π― Enforcing Conditional MFA in Auth0 Using Actions
We recently implemented Multi-Factor Authentication (MFA) in Auth0, but only for specific applications. Rather than enforcing MFA globally, we used Auth0 Actions to apply MFA conditionally based on the client_id
.
Hereβs exactly how we got it working β code and configuration included.
β The Goal
Enable MFA only for specific applications in Auth0, without turning it on globally.
π§ Why Use Actions?
By default, enabling MFA globally affects all applications. If you want fine-grained control, like MFA only for one app, the best solution is to:
- Disable global MFA
- Use Actions β Triggers β Login flow
- Enforce MFA based on
client_id
πΎοΈ The Working Code Snippet
Hereβs the Auth0 Action code that worked perfectly:
/**
* Handler that will be called during the Post Login flow.
*
* @param {Event} event - Details about the login attempt.
* @param {PostLoginAPI} api - Interface for interacting with the Auth0 API.
*/
exports.onExecutePostLogin = async (event, api) => {
// Define Client IDs for apps that should require MFA
const appsRequiringMFA = [
'YOUR_CLIENT_ID_FOR_APP_1',
'YOUR_CLIENT_ID_FOR_APP_2'
];
const clientId = event.client?.client_id;
// Check if current application requires MFA
if (appsRequiringMFA.includes(clientId)) {
// Enforce MFA only if it's not already done in this session
const alreadyUsedMFA = event.authentication?.methods?.some(
method => method.name === 'mfa'
);
if (!alreadyUsedMFA) {
api.multifactor.enable('any');
}
}
};
πͺ How to Enable It
Once your Action is created and deployed, you still need to enable it manually in the Auth0 dashboard:
1. Go to Actions β Flows β Login
2. Drag your custom Action into the Login flow
3. Click Deploy to save the updated flow
π‘ Tip: Set global MFA to βNeverβ in
Security β Multi-factor Auth
to avoid conflicts.
π Summary
- β
Write an Auth0 Action using
api.multifactor.enable("any")
- β
Check
event.client.client_id
to apply it selectively - β Drag the Action into the Login flow
- β Deploy the flow
- β Leave global MFA set to Never
Now your app users will only be prompted for MFA if they log into the designated client β simple, secure, and scoped.
For more advanced Auth0 Actions and authentication scenarios, refer to the Auth0 documentation.
Written with β€οΈ By Jazzed Technology
Happy authenticating!