apps/docs/content/guides/auth/auth-mfa/phone.mdx
Phone multi-factor authentication involves a shared code generated by Supabase Auth and the end user. The code is delivered via a messaging channel, such as SMS or WhatsApp, and the user uses the code to authenticate to Supabase Auth.
The phone messaging configuration for MFA is shared with phone auth login. The same provider configuration that is used for phone login is used for MFA. You can also use the Send SMS Hook if you need to use an MFA (Phone) messaging provider different from what is supported natively.
Below is a flow chart illustrating how the Enrollment and Verify APIs work in the context of MFA (Phone).
<Image alt="Diagram showing the flow of Multi-Factor authentication" src={{ light: '/docs/img/guides/auth-mfa/auth-mfa-phone-flow.svg', dark: '/docs/img/guides/auth-mfa/auth-mfa-phone-flow.svg', }} containerClassName="max-w-[700px]" width={93} height={150} />
An enrollment flow provides a UI for users to set up additional authentication factors. Most applications add the enrollment flow in two places within their app:
As far as possible, maintain a generic flow that you can reuse in both cases with minor modifications.
Enrolling a factor for use with MFA takes three steps for phone MFA:
supabase.auth.mfa.enroll().supabase.auth.mfa.challenge() API. This sends a code via SMS or WhatsApp and prepares Supabase Auth to accept a verification code from the user.supabase.auth.mfa.verify() API. supabase.auth.mfa.challenge() returns a challenge ID.
This verifies that the code issued by Supabase Auth matches the code input by the user. If the verification succeeds, the factor
immediately becomes active for the user account. If not, you should repeat
steps 2 and 3.Below is an example that creates a new EnrollMFA component that illustrates the important pieces of the MFA enrollment flow.
supabase.auth.mfa.enroll() API is
called once to start the process of enrolling a new factor for the current
user.supabase.auth.mfa.challenge() API and the
code from the user is submitted for verification using the
supabase.auth.mfa.verify() challenge.onEnabled is a callback that notifies the other components that enrollment
has completed.onCancelled is a callback that notifies the other components that the user
has clicked the Cancel button.export function EnrollMFA({
onEnrolled,
onCancelled,
}: {
onEnrolled: () => void
onCancelled: () => void
}) {
const [phoneNumber, setPhoneNumber] = useState('')
const [factorId, setFactorId] = useState('')
const [verifyCode, setVerifyCode] = useState('')
const [error, setError] = useState('')
const [challengeId, setChallengeId] = useState('')
const onEnableClicked = () => {
setError('')
;(async () => {
const verify = await auth.mfa.verify({
factorId,
challengeId,
code: verifyCode,
})
if (verify.error) {
setError(verify.error.message)
throw verify.error
}
onEnrolled()
})()
}
const onEnrollClicked = async () => {
setError('')
try {
const factor = await auth.mfa.enroll({
phone: phoneNumber,
factorType: 'phone',
})
if (factor.error) {
setError(factor.error.message)
throw factor.error
}
setFactorId(factor.data.id)
} catch (error) {
setError('Failed to Enroll the Factor.')
}
}
const onSendOTPClicked = async () => {
setError('')
try {
const challenge = await auth.mfa.challenge({ factorId })
if (challenge.error) {
setError(challenge.error.message)
throw challenge.error
}
setChallengeId(challenge.data.id)
} catch (error) {
setError('Failed to resend the code.')
}
}
return (
<>
{error && <div className="error">{error}</div>}
<input
type="text"
placeholder="Phone Number"
value={phoneNumber}
onChange={(e) => setPhoneNumber(e.target.value.trim())}
/>
<input
type="text"
placeholder="Verification Code"
value={verifyCode}
onChange={(e) => setVerifyCode(e.target.value.trim())}
/>
<input type="button" value="Enroll" onClick={onEnrollClicked} />
<input type="button" value="Submit Code" onClick={onEnableClicked} />
<input type="button" value="Send OTP Code" onClick={onSendOTPClicked} />
<input type="button" value="Cancel" onClick={onCancelled} />
</>
)
}
Once a user has logged in via their first factor (email+password, magic link, one time password, social login etc.) you need to perform a check if any additional factors need to be verified.
This can be done by using the supabase.auth.mfa.getAuthenticatorAssuranceLevel() API. When the user signs in and is redirected back to your app, you should call this method to extract the user's current and next authenticator assurance level (AAL).
Therefore if you receive a currentLevel which is aal1 but a nextLevel of aal2, the user should be given the option to go through MFA.
Below is a table that explains the combined meaning.
| Current Level | Next Level | Meaning |
|---|---|---|
aal1 | aal1 | User does not have MFA enrolled. |
aal1 | aal2 | User has an MFA factor enrolled but has not verified it. |
aal2 | aal2 | User has verified their MFA factor. |
aal2 | aal1 | User has disabled their MFA factor. (Stale JWT.) |
Adding the challenge step to login depends heavily on the architecture of your app. However, a fairly common way to structure React apps is to have a large component (often named App) which contains most of the authenticated application logic.
This example will wrap this component with logic that will show an MFA challenge screen if necessary, before showing the full application. This is illustrated in the AppWithMFA example below.
function AppWithMFA() {
const [readyToShow, setReadyToShow] = useState(false)
const [showMFAScreen, setShowMFAScreen] = useState(false)
useEffect(() => {
;(async () => {
try {
const { data, error } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel()
if (error) {
throw error
}
console.log(data)
if (data.nextLevel === 'aal2' && data.nextLevel !== data.currentLevel) {
setShowMFAScreen(true)
}
} finally {
setReadyToShow(true)
}
})()
}, [])
if (readyToShow) {
if (showMFAScreen) {
return <AuthMFA />
}
return <App />
}
return <></>
}
supabase.auth.mfa.getAuthenticatorAssuranceLevel() does return a promise.
Don't worry, this is a very fast method (microseconds) as it rarely uses the
network.readyToShow only makes sure the AAL check completes before showing any
application UI to the user.App component is finally rendered on
screen.Below is the component that implements the challenge and verify logic.
function AuthMFA() {
const [verifyCode, setVerifyCode] = useState('')
const [error, setError] = useState('')
const [factorId, setFactorId] = useState('')
const [challengeId, setChallengeId] = useState('')
const [phoneNumber, setPhoneNumber] = useState('')
const startChallenge = async () => {
setError('')
try {
const factors = await supabase.auth.mfa.listFactors()
if (factors.error) {
throw factors.error
}
const phoneFactor = factors.data.phone[0]
if (!phoneFactor) {
throw new Error('No phone factors found!')
}
const factorId = phoneFactor.id
setFactorId(factorId)
setPhoneNumber(phoneFactor.phone)
const challenge = await supabase.auth.mfa.challenge({ factorId })
if (challenge.error) {
setError(challenge.error.message)
throw challenge.error
}
setChallengeId(challenge.data.id)
} catch (error) {
setError(error.message)
}
}
const verifyCode = async () => {
setError('')
try {
const verify = await supabase.auth.mfa.verify({
factorId,
challengeId,
code: verifyCode,
})
if (verify.error) {
setError(verify.error.message)
throw verify.error
}
} catch (error) {
setError(error.message)
}
}
return (
<>
<div>Please enter the code sent to your phone.</div>
{phoneNumber && <div>Phone number: {phoneNumber}</div>}
{error && <div className="error">{error}</div>}
<input
type="text"
value={verifyCode}
onChange={(e) => setVerifyCode(e.target.value.trim())}
/>
{!challengeId ? (
<input type="button" value="Start Challenge" onClick={startChallenge} />
) : (
<input type="button" value="Verify Code" onClick={verifyCode} />
)}
</>
)
}
supabase.auth.mfa.listFactors(). Don't worry this method is also very quick
and rarely uses the network.listFactors() returns more than one factor (or of a different type) you
should present the user with a choice. For simplicity this is not shown in
the example.onSuccess callback, which
will show the authenticated App component on screen.Each code is valid for up to 5 minutes, after which a new one can be sent. Successive codes remain valid until expiry. When possible choose the longest code length acceptable to your use case, at a minimum of 6. This can be configured in the Authentication Settings.
Be aware that Phone MFA is vulnerable to SIM swap attacks where an attacker will call a mobile provider and ask to port the target's phone number to a new SIM card and then use the said SIM card to intercept an MFA code. Evaluate the your application's tolerance for such an attack. You can read more about SIM swapping attacks here
<$Show if="billing:all"> <$Partial path="billing/pricing/pricing_mfa_phone.mdx" /> </$Show>