Login Validation Lambda
On this page
During a login request, FusionAuth runs validations such as checking credentials, or checking a one-time code during a multi-factor login. With this lambda, you can add your own validation to a login request.
The login validation lambda has access to the user record, to the user's registration for the application when one exists, and to metadata about the request. You can use Lambda HTTP Connect in this lambda to validate against external resources. Any latency you add slows the login for your users.
When you create a lambda in the Admin UI, FusionAuth provides an empty function for you to implement.
Lambda Structure#
When you create the lambda with the API, make sure the function has the following signature:
function validate(result, user, registration, context) {
// Lambda code goes here
}
This lambda must contain a function named validate that accepts the following parameters:
result: an object used for returning validation errors. You can modify this object.user: the FusionAuth User object. This object is read-only.registration: the FusionAuth UserRegistration object. This object is read-only.context: an object containing context for the current request. This object is read-only.
The result object contains an Errors object. For more information about the user and registration objects, see the User API and Registration API.
To deny a login attempt, add one or more field or general errors to the result. For the error schema, see the API Errors documentation.
The context Object#
The read-only context object has the following fields:
authenticationType: the method used to authenticate the user. The possible values follow this list.identityProvider: the Identity Provider for a login through a third-party IdP. FusionAuth only setsidentityProviderfor those logins. TheidentityProviderobject has the following fields:id: the Id of the IdP.name: the name of the IdP.type: the type of the IdP.
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.
Assigning The Lambda#
After you create the lambda, assign the lambda to a Tenant. In the Admin UI, find the Login validation lambda field on the Security tab of the Tenant configuration.
With the Tenant API, set tenant.lambdaConfiguration.loginValidationId to the lambda Id.
Example Lambdas#
Block Past Due Accounts#
The following lambda rejects logins from accounts that your billing system marks as past due. The lambda reads accountStatus from user.data, so your billing system needs to set that field with the User API. Past due users can still log in to the billing portal to pay. The lambda compares registration.applicationId to the billing portal's Id. The registration is null when the user isn't registered for the application, so the lambda checks for null first.
// rejects logins from past due accounts, except to the billing portal so the user can still pay
var billingApplicationId = 'replace-with-your-billing-application-id';
function validate(result, user, registration, context) {
if (!user.data || user.data.accountStatus !== 'pastDue') {
return;
}
if (registration && registration.applicationId === billingApplicationId) {
return;
}
result.errors.generalErrors = [{
code: '[LoginRestricted]',
message: 'Account is past due, please contact accounts payable.'
}];
}Require Single Sign-On for Employees#
The following lambda makes users with a piedpiper.com email address log in through the company Identity Provider. The lambda rejects password, passwordlessAny login that doesn't ask for a password, such as passkeys or one-time passwords. The Passwordless API handles one-time passwords only., and one-time password logins for those users, and logins through any other Identity Provider.
FusionAuth runs the lambda again when the user completes an MFA challenge. During that second run, authenticationType keeps the value from the first step, but identityProvider is absent. The lambda accepts that case, so an employee who logs in through the company Identity Provider can finish MFA.
// makes employees log in through the company identity provider instead of with local credentials
var employeeDomain = 'piedpiper.com';
var companyIdentityProviderId = 'replace-with-your-identity-provider-id';
var localLoginTypes = ['PASSWORD', 'PASSWORDLESS', 'ONE_TIME_PASSWORD'];
function validate(result, user, registration, context) {
var email = (user.email || '').toLowerCase();
if (email.slice(-(employeeDomain.length + 1)) !== '@' + employeeDomain) {
return;
}
// the MFA step of an IdP login has the IdP's type but no identityProvider
var otherIdentityProvider = context.identityProvider && context.identityProvider.id !== companyIdentityProviderId;
if (localLoginTypes.indexOf(context.authenticationType) === -1 && !otherIdentityProvider) {
return;
}
console.info('Rejected a ' + context.authenticationType + ' login for employee ' + user.id + '.');
result.errors.generalErrors = [{
code: '[SSORequired]',
message: 'Log in with Pied Piper single sign-on.'
}];
}Localization#
When you call a Login APIThe FusionAuth API that logs a user in without the hosted login pages. directly and the lambda adds errors to result, the API responds with a 400 status code. The JSON response contains the errors object the lambda returned.
The FusionAuth hosted login pagesThe login, registration, password recovery, and multi-factor authentication pages that FusionAuth serves. A Theme controls the look of the pages. can localize the message. FusionAuth chooses the message in the following order:
- When your theme defines the message key from the
codefield, FusionAuth displays the localized message from the theme. - Otherwise, FusionAuth displays the
messagethe lambda set. - When the lambda set no
message, FusionAuth displays the message key from thecodefield.
With the past due example, the user sees the message Account is past due, please contact accounts payable. by default.
To localize the message, or to make the message friendlier, add the following message to your theme:
[LoginRestricted]=Looks like you forgot to pay your bill. Please call 1-800-555-5555 for assistance.
With this change, the user sees Looks like you forgot to pay your bill. Please call 1-800-555-5555 for assistance..
Related
Learn about lambdas, the JavaScript functions that customize how FusionAuth logs users in and issues tokens.
Learn how to add custom claims to the access tokens and Id tokens FusionAuth issues.
Learn how to call an external API from a lambda.
Learn how to allow or reject the CIMD clients that register with a CIMD domain.