MFA Requirement Lambda
On this page
This feature requires an Enterprise plan.
During logins, password changes, and MFA Status API calls, FusionAuth decides whether to challenge the user with one of the user's MFA methods. With this lambda, you can change FusionAuth's MFA decision for the user or trigger a suspicious login event.
The MFA Requirement Lambda has access to the following information:
- the access token returned by FusionAuth as the result of a successful authentication
- the action being taken
- FusionAuth's out of the box MFA decision
- the user record
- the user's registration for the application they're trying to authenticate to
- the MFA policy settings on the tenant and application
- metadata about the request
You can use Lambda HTTP Connect to access external resources from this lambda. Keep external calls to a minimum, because every delay slows the request for your users.
Lambda Structure#
All lambda implementations must contain a method with the following signature:
function checkRequired(result, user, registration, context) {
// Lambda code goes here
}
The checkRequired function must accept the following parameters:
result: an object used for returning modified MFA requirements back to FusionAuth.user: the read-only FusionAuth User object.registration: the FusionAuthUserRegistrationobject. This parameter isnullwhen the request doesn't include an application, or when the user isn't registered for the application, such as when an existing user logs in to an application with SSO for the first time. This object is read-only.context: an object containing context for the current request. This object is read-only and contains several optional fields.
For more information about user and registration, see the User API and Registration API documentation.
result is of type RequiredLambdaResult, with the following structure:
class RequiredLambdaResult {
/**
* This value will be set to FusionAuth's out of the box decision on whether an MFA challenge
* should be required for the user. Mutate this to change the decision.
* @type {boolean}
*/
required;
/**
* To force a suspicious login event to be created, set this to true. This will have no effect
* unless the action is `login`.
* @type {boolean}
*/
sendSuspiciousLoginEvent;
}
The context Object#
The read-only context object has the following fields:
accessToken: the encoded JWT. FusionAuth setsaccessTokenwhen a JWT authenticates the request to/api/user/change-password, or when the request to/api/two-factor/statusincludes atoken. Otherwise,accessTokenisnull.action: the action that runs the lambda:login,changePassword, orstepUp. Logins and password changes through FusionAuth APIs or hosted pages always useloginorchangePassword. To usestepUp, passstepUpin theactionfield of the MFA Status API.application: the FusionAuth Application object, without secrets. The value isnullunless the API request that runs the lambda includes anapplicationId.authenticationThreats: the authentication threats FusionAuth detected for the request. FusionAuth only fills the list for theloginandchangePasswordactions, and only with the risk signals enabled in the Tenant's client risk configuration. The list is always empty for the MFA Status API. Currently, FusionAuth only addsImpossibleTravel, when the impossible travel signal isHIGH. UseclientRiskfor the other signals. The possible values areBlocklistedIp,BotDetected,DormantAccount,DormantPassword,ImpossibleTravel,RecentIdentityChange,RecentPasswordChange,SuspiciousUserAgent,UnrecognizedDevice, andUntrustedDevice.authenticationType: Available since1.63.0the method used to authenticate the user. FusionAuth only setsauthenticationTypefor theloginaction. The possible values follow this list.clientRisk: Available since1.68.0the client risk for the user, calculated from a combination of Intelligent MFA signals. TheclientRiskobject has the following field:status: the risk score:LOW,MEDIUM,HIGH, orNOT_AVAILABLE. The value isNOT_COMPUTEDwhen your plan doesn't include Intelligent MFA.
eventInfo: information about the request. The value can benull, depending on what the API request provides. TheeventInfoobject has the following fields:data: additional data for the event, as a map. The value can benull.deviceDescription: the description of the device.deviceName: the name of the device.deviceType: the type of the device.ipAddress: the IP address of the request.location: the location of the IP address, with the fieldscity,country,latitude,longitude,region, andzipcode. FusionAuth only setslocationwith Advanced Threat Detection.os: the operating system of the device.userAgent: the user agent of the request.
mfaTrust: the user's existing MFA trust, from a cookie on the hosted pages or fromtwoFactorTrustIdin the API request. The value isnullwithout an existing trust, and when FusionAuth detects impossible travel with high risk. ThemfaTrustobject has the following fields:applicationId: the Id of the application the trust was first established for.attributes: additional attributes of the trust, as a map.expirationInstant: the instant the trust expires.id: thetwoFactorTrustId.insertInstant: the instant FusionAuth created the trust.startInstants: the instants the trust started, with the following fields:applications: a map from each application Id to the instant the user completed/api/two-factor/loginfor the application.tenant: the first instant the trust was established for the user's Tenant.
state: additional state of the trust, as a map.tenantId: the Id of the user's Tenant.userId: the Id of the user.
policies: the MFA policies for the Tenant and the application, with the following fields:applicationLoginPolicy: the application's MFA login policy:ChallengeOnHighRisk,ChallengeOnMediumRisk,Disabled,Enabled, orRequired. The value isnullwhen the request doesn't include an application.applicationMultiFactorTrustPolicy: the application's MFA trust policy:Any,This, orNone. The value isnullwhen the request doesn't include an application.tenantLoginPolicy: the Tenant's MFA login policy, with the same values asapplicationLoginPolicy.
services: Available since1.64.0access to secrets throughcontext.services.secrets.get('<secret-name>').
The possible values for authenticationType are:
APPLE- The user was authenticated using Apple.APPLICATION_TOKEN- The user was authenticated using an Application Authentication Token.EpicGames- The user was authenticated using Epic Games.FACEBOOK- The user was authenticated using Facebook.FEDERATED_JWT- The user was authenticated using a JWT from an external source.GENERIC_CONNECTOR- The user was authenticated using a generic connector.GOOGLE- The user was authenticated using Google.HYPR- The user was authenticated using HYPR.JWT_SSO- A valid JWT associated with one application was exchanged for another JWT associated with a different application.LDAP_CONNECTOR- The user was authenticated using an LDAP connector.LINKEDIN- The user was authenticated using LinkedIn.Nintendo- The user was authenticated using Nintendo.ONE_TIME_PASSWORD- The user was authenticated using a one-time password.OPENID_CONNECT- The user was authenticated using OIDC.PASSWORD- The user was authenticated using a loginId and password combination.PASSWORDLESS- The user was authenticated using a passwordless login link.PING- The user was authenticated using aPUTrequest on the Login API. This is used to record a login event without prompting for credentials, such as when the FusionAuth SSO session is used.REFRESH_TOKEN- The user requested a new JWT using a refresh token.REGISTRATION- The user was created using the Registration API.SAMLv2- The user was authenticated using SAMLv2.SAMLv2IdpInitiated- The user was authenticated using SAMLv2 IdP Initiated login.SonyPSN- The user was authenticated using Sony.Steam- The user was authenticated using Steam.TWITTER- The user was authenticated using Twitter.Twitch- The user was authenticated using Twitch.USER_CREATE- The user was created using the User API.WebAuthn- The user was authenticated using a passkey.Xbox- The user was authenticated using Xbox.
For more information about context.application, see the Application API reference.
For more information on advanced threat protection, see the Advanced Threat Detection documentation.
Errors and Ignored Results#
If the lambda throws an exception, FusionAuth requires MFA and writes the exception to the Event Log.
For the login and changePassword actions, FusionAuth ignores the lambda's result when the Tenant has no MFA methods enabled. FusionAuth then doesn't send a suspicious login event either. For the stepUp action, FusionAuth always uses the lambda's result.
Assigning The Lambda#
After you create the lambda, assign the lambda to a Tenant. In the Admin UI, find the MFA requirement lambda field on the Multi-Factor tab of the Tenant configuration.
With the Tenant API, set tenant.lambdaConfiguration.multiFactorRequirementId to the lambda Id.
You can also assign a lambda to an application. An application lambda requires the Application MFA feature, which is part of the Enterprise plan. Without the feature, FusionAuth returns a validation error when you save the application. When the request includes an application with an assigned lambda, FusionAuth runs the application's lambda instead of the Tenant's lambda for every action. When the application has no lambda assigned, FusionAuth runs the Tenant's lambda. When the Tenant has no MFA methods enabled, FusionAuth always runs the Tenant's lambda. In the Admin UI, find the MFA requirement lambda field on the Multi-Factor tab of the Application configuration.
With the Application API, set application.lambdaConfiguration.multiFactorRequirementId to the lambda Id.
Example Lambdas#
Challenge Risky Logins#
The following lambda requires MFA when FusionAuth rates the login as MEDIUM or HIGH risk, or reports impossible travel. For HIGH risk logins and impossible travel, the lambda also sets sendSuspiciousLoginEvent. For every other login, the lambda keeps FusionAuth's decision. FusionAuth only computes clientRisk with Intelligent MFA, and only fills authenticationThreats with Advanced Threat Detection. Without those features, the lambda keeps FusionAuth's decision.
// challenges risky logins and flags the riskiest ones, and keeps the default decision otherwise
function checkRequired(result, user, registration, context) {
var risk = context.clientRisk && context.clientRisk.status;
// ImpossibleTravel is the only threat FusionAuth reports to this lambda
var impossibleTravel = (context.authenticationThreats || []).indexOf('ImpossibleTravel') !== -1;
if (risk === 'HIGH' || risk === 'MEDIUM' || impossibleTravel) {
result.required = true;
}
// sendSuspiciousLoginEvent only applies to the login action
if (context.action === 'login' && (risk === 'HIGH' || impossibleTravel)) {
result.sendSuspiciousLoginEvent = true;
}
}Always Challenge Privileged Users#
The following lambda requires MFA for members of an mfa_required group, and for users with an admin role in the application. The registration is null when the request doesn't include an application, so the lambda only checks roles when a registration exists.
// always challenges admins and members of the mfa_required group
var mfaRequiredGroupId = 'replace-with-your-mfa-group-id';
var adminRoles = ['admin', 'billing-admin'];
function checkRequired(result, user, registration, context) {
var inGroup = (user.memberships || []).some(function (membership) {
return membership.groupId === mfaRequiredGroupId;
});
// registration is null when the request has no application or the user isn't registered
var roles = (registration && registration.roles) || [];
var isAdmin = roles.some(function (role) {
return adminRoles.indexOf(role) !== -1;
});
if (inGroup || isAdmin) {
result.required = true;
}
}Related
API documentation for the FusionAuth Complete Multi-Factor Authentication API.
Learn about the APIs for enabling and disabling multi-factor authentication for users.
API documentation for the FusionAuth Send a Multi-Factor Code During Login or Step Up API.
API documentation for the FusionAuth Start Multi-Factor API.