Skip to main content

How it works

caution
  • SuperTokens is not yet optimised for 2FA implementation, so you have to add a lot of customisations for it to work. We are working on improving the development experience for 2FA as well as adding more factors like TOTP. Stay tuned.
  • A demo app that uses the pre built UI can be found on our GitHub.

You need to start by choosing your first factor auth. This can be any of the auth recipes we support. A common choice is the thirdpartyemailpassword recipe 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 createNewSession function in the Session recipe to store the fact that only the first factor is complete. We do this by adding the SecondFactorClaim to the session which will default to false.
  • After the second factor is completed, we will update the session and set SecondFactorClaim to true.
  • To make sure that application APIs are only accessible post 2FA is completed, we will add a SecondFactorClaim validator to the global validators by overriding getGlobalClaimValidators in the Session recipe. This will check if the second factor has been completed whenever verifySession or getSession is called.
  • Similarly, to protect frontend routes, we will add the SecondFactorClaim validator to the global validators so that all components wrapped with the SessionAuth component 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 UserMetadata recipe to store information about the second factor auth's identification. In the example app, we use phone number SMS OTP as the second factor, so we store the user's phone number using the UserMetadata recipe, and only send OTPs to that number during sign in. The phone number itself is obtained during the sign up flow.
important

In the subsequent sections, we will see how to implement 2fa with the first factor being social and email / password login, and the second factor being phone SMS OTP.

If you require a different set of factors or behaviour, you can take inspiration from this guide.

Looking for older versions of the documentation?
Which UI do you use?
Custom UI
Pre built UI