How it works
Implement multi-factor authentication using customizable auth recipes, including session management and second factor validation.
You need to start by choosing your first factor auth. This can be any of the auth recipes we support. A common choice is to combine the thirdparty and emailpassword recipes, which allows users to sign in with social or email / password login.
For the second factor, whilst you can choose any of our auth recipes as well, the most common choice is the Passwordless recipe, using which, you can send SMS or email OTP (or magic links) to the user.
You will also need to use our Session recipe which can be used to store information about which factors have been completed by the user for the current session. This will be integral to our implementation.
As a high level flow, we will customise these recipes in the following way:
- After the first factor is completed, we will override the
createNewSessionfunction in the Session recipe to store the fact that only the first factor is complete. We do this by adding theSecondFactorClaimto the session which will default to false. - After the second factor is completed, we will update the session and set
SecondFactorClaimto true. - To make sure that application APIs are only accessible post 2FA is completed, we will add a
SecondFactorClaimvalidator to the global validators by overridinggetGlobalClaimValidatorsin the Session recipe. This will check if the second factor has been completed wheneververifySessionorgetSessionis called. - Similarly, to protect frontend routes, we will add the
SecondFactorClaimvalidator to the global validators ensuring that all components wrapped with theSessionAuthcomponent will check that 2FA is completed. If not, we can then reroute the user to the second factor screen. - We also need to use the
UserMetadatarecipe to store information about the second factor authentication’s identification. In the example app, we use phone number SMS OTP as the second factor, therefore we store the user’s phone number using theUserMetadatarecipe, and only send OTPs to that number during sign in. The phone number itself is obtained during the sign up flow.