Prompt users to authenticate their primary factor
First, you’ll need to prompt users to complete their first method of authentication. For the purposes of this guide, we’ll use Passwords as our primary authentication factor.We’ll also assume that the user already has an account with a password and a verified email address. If the user’s email address has not yet been verified, you will receive a In the Authenticate password response, you’ll receive a
too_many_unverified_factors error upon adding a new phone number.Create a UI to prompt the user for their email address and password. Upon submission, call the Authenticate password method:session object with details about the user’s new Stytch Session. Within the session object, you’ll see an authentication_factors array with a password factor in it. Note that there is only one factor present in the authentication_factors array, indicating that the user has not yet completed MFA.Prompt users to authenticate their secondary factor
In this guide, we’ll use SMS OTP as our secondary factor.Passwords and SMS OTP are a good combination of factors, because they confirm your user’s identity in two different ways. Note that Passwords and an email-based authentication method are not a secure combination of factors, given that a user’s password can be reset if a bad actor has access to the user’s email inbox.Create a UI for the user to enter their phone number if it’s not already present on their Stytch User, and send the user an OTP code via the Send OTP by SMS method:Next, surface a UI for the user to input the OTP code that they receive, and call the Authenticate OTP endpoint with the The new
method_id from the stytchClient.otps.sms.send response and the OTP code:session object’s authentication_factors array will now contain both a password factor and a new otp factor:If you authenticate either factor on the backend, make sure to hydrate the frontend SDK with the updated session data by passing the newest
session_token into the frontend Update session method, followed by a call to the frontend Authenticate session method. For security purposes, the original session will be revoked shortly after the user authenticates their second factor.Enforce MFA in your application's authorization logic
In order to enforce that users complete MFA before accessing protected content, you’ll need to inspect the You can also gate frontend content based on the Session’s authentication factors in order to achieve your desired UI. Below is a simplified example:
authentication_factors array after authenticating the Stytch Session in your application’s backend authorization logic and make sure that the required factors are present. Below is a simplified example of a backend authorization endpoint: