Appearance
Implementing MFA with custom UIs
If you'd like to implement wallet MFA in your application using your own UIs, follow this guide. At a high-level, your app must set up two core user flows:
- Enrolling in MFA, with the user's desired authentication method(s)
- Completing MFA, when it is required by the embedded wallet
Enrolling in MFA
To enroll your users in MFA, use the initMfaEnrollment
and submitMfaEnrollment
methods returned by the useMfaEnrollment
hook:
tsx
const {initMfaEnrollment, submitMfaEnrollment} = useMfaEnrollment();
Currently, users can enroll in three MFA methods:
- SMS, where users authenticate with a 6-digit MFA code sent to their phone number
- TOTP, where users authenticate with a 6-digit MFA code from an authentication app, like Authy or Google Authenticator
- Passkey, where users verify with a previously registered passkey, generally through biometric authentication on their device
Follow the specific instructions below based on which method you'd like your user to enroll in!
SMS
First, initiate enrollment by prompting your user to enter the phone number they'd like to use for MFA. Then, call Privy's initMfaEnrollment
method. As a parameter to this initMfaEnrollment
, pass a JSON object with the method
param set to sms
and a phoneNumber
field that contains the user's provide phone number as a string.
tsx
// Prompt the user for their phone number
const phoneNumberInput = 'insert-phone-number-from-user';
// Send an enrollment code to their phone number
await initMfaEnrollment({method: 'sms', phoneNumber: phoneNumberInput});
Once initMfaEnrollment
is called with a valid phoneNumber
, Privy will then send a 6-digit MFA enrollment code to the provided number. This method returns a Promise
that will resolve to void
if the code was successfully sent, or will reject with an error
if there was an error sending the code (e.g. invalid phone number).
Next, prompt the user to enter the 6-digit code that was sent to their phone number, and use the submitMfaEnrollment
method to complete enrollment of that phone number. As a parameter to submitMfaEnrollment
, you must pass a JSON object with both the original phoneNumber
that the user enrolled, and the mfaCode
they received at that number.
tsx
// Prompt the user for the code sent to their phone number
const mfaCodeInput = 'insert-mfa-code-received-by-user';
await submitMfaEnrollment({
method: 'sms',
phoneNumber: phoneNumberInput, // From above
code: mfaCodeInput,
});
This method returns a Promise
that will resolve to void
if the provided code is correct and the user has successfully enrolled this phone number in MFA, or will reject with an error
if there was an error. See the Handling errors with code submission section of this guide for how to best handle possible errors.
See an end-to-end example of enrolling users in MFA with SMS 👇
The component below serves as a reference implementation for how to enroll your users in MFA with SMS!
tsx
import {useMfaEnrollment} from '@privy-io/expo';
export default function MfaEnrollmentWithSms() {
const {initMfaEnrollment, submitMfaEnrollment} = useMfaEnrollment();
const [phoneNumber, setPhoneNumber] = useState<string | null>(null);
const [mfaCode, setMfaCode] = useState<string | null>(null);
const [pendingMfaCode, setPendingMfaCode] = useState<boolean>(false);
// Handler for when the user enters their phone number to enroll in MFA.
const onEnteredPhoneNumber = () => {
await initMfaEnrollmen({method: 'sms', phoneNumber: phoneNumber}); // Sends an MFA code to the `phoneNumber`
setPendingMfaCode(true);
}
// Handler for when the user enters the MFA code sent to their phone number.
const onEnteredMfaCode = () => {
await submitMfaEnrollment({ method: 'sms', phoneNumber: phoneNumber, code: mfaCode});
// See the "Handling errors with code submission" section of this guide
// for details on how to handle errors raised by `submitEnrollmentWithSms`
setPendingMfaCode(false);
}
// If no MFA code has been sent yet, prompt the user for their phone number to enroll
if (!pendingMfaCode) {
// Input field for the user to enter the phone number they'd like to enroll for MFA
return (
<YStack gap={12}>
<Input value={mfaCode}
onChangeText={setPhoneNumber}
flex={1}
keyboardType="number-pad"
/>
<Button onPress={onEnteredPhoneNumber} flex={1}>
<Text>Enroll a Phone with MFA</Text>
</Button>
</YStack>
)
}
// Input field for the user to enter the MFA code sent to their phone number
return
<>
<Input value={mfaCode} onChangeText={setMfaCode}/>
<Button onPress={onEnteredMfaCode}><Text>Submit Enrollment Code</Text></Button>
</>;
}
INFO
If your app has enabled SMS as a possible login method, users will not be able to enroll SMS as a valid MFA method.
SMS can be either be used as a login method to secure user accounts, or as an MFA method for additional security on the users' wallets, but cannot be used for both.
TOTP
First, initiate enrollment by calling Privy's initMfaEnrollment
method with a JSON parameter of {method: 'totp'}
. This method returns a Promise
for an authUrl
that the user will need in order to complete enrollment.
tsx
const {authUrl} = await initMfaEnrollment({method: 'totp'});
Then, to have the user enroll, you can display the TOTP authUrl
as a QR code to the user, and prompt them to scan it with their TOTP client (commonly, a mobile app like Google Authenticator or Authy)
TIP
You can directly pass in the authUrl
from above into a library like expo-linking
to deep link into a TOTP application for MFA.
Once your user has successfully linked into their TOTP application, a code will be generated for the TOTP verification. Prompt the user to enter this code in your app, and call Privy's submitMfaEnrollment
method. As a parameter to submitMfaEnrollment
, pass a JSON object with an mfaCode
field that contains the MFA code from the user as a string:
tsx
const mfaCodeInput = 'insert-mfa-code-from-user-totp-app'; // Prompt the user for the code in their TOTP app
await submitMfaEnrollment({method: 'totp', mfaCode: mfaCodeInput});
This method returns a Promise
that will resolve to void
if the entered mfaCode
was correct, and will reject with an error otherwise. See the Handling errors with code submission section of this guide for how to best handle possible errors.
See an end-to-end example of enrolling users in MFA with TOTP 👇
The component below serves as a reference implementation for how to enroll your users in MFA with TOTP!
tsx
import {useMfaEnrollment} from '@privy-io/expo';
export default function MfaEnrollmentWithTotp() {
const {initMfaEnrollment, submitMfaEnrollment} = useMfaEnrollment();
const [totpAuthUrl, setTotpAuthUrl] = useState<string | null>(null);
const [mfaCode, setMfaCode] = useState<string | null>(null);
// Handler for when the user is ready to enroll in TOTP MFA
const onGenerateTotpUrl = async () => {
const {authUrl} = await initMfaEnrollment({method: 'totp'});
setTotpAuthUrl(authUrl);
}
// Handler for when the user enters the MFA code from their TOTP client
const onMfaEnrollmentSubmit = async () => {
await submitMfaEnrollment({method: 'totp', code: mfaCode});
// See the "Handling errors with code submission" section of this guide
// for details on how to handle errors raised by `submitEnrollmentWithTotp`
}
return(
{/* QR code for the user to scan */}
<YStack gap={12}>
<Text>TOTP MFA Enrollment</Text>
{
// Check to see if the totpUrl is generated
!!totpUrl && <Text onPress={() => Linking.openURL(totpUrl)} >{totpUrl}</Text>
<XStack gap={12}>
<Input
value={totpCode}
onChangeText={setTotpCode}
flex={1}
keyboardType="number-pad"
/>
{// Once the TOTP code is received in the authenticator app and input above, submit for enrollment}
<Button onPress={onMfaEnrollmentSubmit} flex={1}>
<Text>Verify OTP</Text>
</Button>
</XStack>
}
</YStack>
);
}
Passkey
TIP
In order to use passkeys as a MFA method, make sure a valid passkey is linked to the user. You can set this up by following the steps here!
First, initiate enrollment by calling Privy's initMfaEnrollment
method with a JSON parameter of {method: 'passkey'}
.. This method returns a Promise
that will resolve to void
indicating success.
tsx
await initMfaEnrollment({method: 'passkey'});
Then, to have the user enroll, you must call Privy's submitMfaEnrollment
method with a list of the user's passkey account credentialIds
. You can find this list by querying the user
's linkedAccounts
array for all accounts of type: 'passkey'
:
tsx
const {user} = usePrivy();
// ...
const credentialIds = user.linked_accounts
.filter((account): account is PasskeyWithMetadata => account.type === 'passkey')
.map((x) => x.credentialId);
await submitMfaEnrollment({method: 'passkey', credentialIds});
This method returns a Promise
that will resolve to void
if the entered credentialIds
were valid and will reject with an error otherwise.
See an end-to-end example of enrolling users in MFA with passkeys 👇
The component below serves as a reference implementation for how to enroll your users in MFA with passkeys!
tsx
import {useMfaEnrollment, usePrivy} from '@privy-io/expo';
export default function MfaEnrollmentWithPasskey() {
const {user} = usePrivy();
const {iniMfaEnrollment, submitMfaEnrollment} = useMfaEnrollment();
const handleEnrollmentWithPasskey = async () => {
await initMfaEnrollment({method: 'passkey'});
const credentialIds = user.linked_accounts
.filter((account): account is PasskeyWithMetadata => account.type === 'passkey')
.map((x) => x.credentialId);
await submitMfaEnrollment({method: 'passkey', credentialIds});
};
return (
<YStack>
<Text>Enable your passkeys for MFA</Text>
{user.linkedAccounts
.filter((account): account is PasskeyWithMetadata => account.type === 'passkey')
.map((account) => (
<Text >ID: {account.id} {' '} Credential ID: {account.credentialId}</div>
))}
{// Initialize and submit the passkey credentials for MFA enrollment in one step }
<Button onPress={handleEnrollmentWithPasskey}>
<Text>Enroll</Text>
</Button>
</YStack>
);
}
Enrolling multiple MFA methods
Privy allows users to register multiple MFA methods (e.g. SMS, TOTP, and passkeys) if they wish.
INFO
If a user already has one MFA method enabled, and wishes to enroll in another (or change their existing MFA method), Privy will require the user to complete MFA with their existing method in order to complete enrollment of the new, additional method.
To ensure your users can complete this flow if required, please make sure you have implemented the Completing MFA logic described below before allowing users to enroll in another MFA method.
This is the generic logic that allows Privy to invoke an MFA flow for your users whenever required (signatures, transactions, and in this case, enrolling a new MFA method). Thereafter, you should not need any other setup to allow users to enroll in additional MFA methods.
Unenrolling MFA methods
Privy also allows users to also delete MFA methods via the unenrollMfa
method returned from the useMfaEnrollment
hook. When invoked, unenrollment methods will require the user to first complete MFA verification, in order to confirm unenrollment. In kind, unenrolling MFA methods requires that you have implemented the Completing MFA logic described below.
These methods return a Promise
that resolves to void
if unenrollment was successful, or rejects with an error
if there was an issue with unenrollment (e.g. user did not complete MFA verification, or user did not have that MFA method enrolled).
tsx
import {useMfaEnrollment} from '@privy-io/expo';
export default function MfaUnenrollment() {
const {unenrollWithSms, unenrollWithTotp} = useMfaEnrollment();
return (
<YStack>
<Button onClick={() => unenrollMfa({method: 'sms'})}>
<Text>Unenroll SMS</Text>
</Button>
<Button onClick={() => unenrollMfa({method: 'totp'})}>
<Text>Unenroll TOTP</Text>
</Button>
<Button onClick={() => unenrollMfa({method: 'passkey'})}>
<Text>Unenroll passkey</Text>
</Button>
</YStack>
);
}
Completing MFA
Once users have successfully enrolled in MFA with Privy, they will be required to complete MFA whenever the private key for their embedded wallet must be used. This includes signing messages and transactions, recovering the embedded wallet on new devices, exporting the wallet's private key, and setting a password on the wallet.
To ensure users can complete MFA when required, your app must do the following:
- Set up a flow to guide the user through completing MFA when required.
- Register an event listener to configure Privy to invoke the flow from step (1) whenever MFA is required.
TIP
Once a user has completed MFA on a given device, they can continue to use the wallet on that device without needing to complete MFA for 15 minutes.
After 15 minutes have elapsed, Privy will require that the user complete MFA again to re-authorize use of the wallet's private key.
Guiding the user through MFA
To set up a flow to have the user complete MFA, use Privy's useMfa
hook.
tsx
const {init, submit, cancel} = useMfa();
This flow has three core components
- Requesting an MFA code be sent to the user's MFA method (
init
) - Submitting the MFA code provided by the user (
submit
) - Cancelling an in-progress MFA flow (
cancel
)
Requesting an MFA challenge
To request an MFA challenge for the current user, call the init
method from the useMfa
hook, passing the user's desired MFA method ('sms'
, 'totp'
, or 'passkey'
) as a parameter.
tsx
const selectedMfaMethod = 'sms'; // Must be 'sms', 'totp' or 'passkey'
await init({method: selectedMfaMethod});
The init
method will then prepare an MFA challenge for the desired MFA method, and returns a Promise
that resolves if the challenge was successfully created, and rejects with an error if there was an issue.
- If the MFA method is
'sms'
, the user will receive an SMS with their MFA code at the phone number they originally enrolled. - If the MFA method is
'totp'
, the user will receive the MFA code within their authenticator app. - If the MFA method is
'passkey'
,init
will return an object with options to pass to the native passkey system
Submitting the MFA verification
Once init
has resolved successfully, prompt the user to get their MFA code from their MFA method and to enter it within your app. Then, call the submit
method from useMfa
. As parameters to submit
, pass the MFA method being used ('sms'
or 'totp'
) and the MFA code that the user entered.
tsx
const mfaCode = 'insert-mfa-code-from-user';
await submit({method: selectedMfaMethod, mfaCode});
When invoked, submit
returns a Promise
that resolves to void
if the user has successfully completed MFA, or rejects with an error if there was an issue completing MFA. See the Handling errors with code submission section of this guide for how to best handle possible errors.
Cancelling the MFA flow
After init
has been called and the corresponding submit
call has not yet occurred, the user may cancel their in-progress MFA flow if they wish.
To cancel the current MFA flow, call the cancel
method from the useMfa
hook.
tsx
cancel();
See a recommended abstraction for guiding users to complete MFA 👇
To simplify the implementation, we recommend abstracting the logic above into a self-contained component that can be used whenever the user needs to complete an MFA flow.
For instance, you might write an MFAModal
component that allows the user to (1) select their desired method of their enrolled MFA methods, (2) request an MFA code, and (3) submit the MFA code to Privy for verification. A sample implementation is below:
tsx
import Modal from 'react-native';
import {
errorIndicatesMfaVerificationFailed,
errorIndicatesMfaMaAttempts,
errorIndicatesMfaTimeout,
MfaMethod,
} from '@privy-io/expo';
type Props = {
// List of available MFA methods that the user has enrolled in
mfaMethods: MfaMethod[];
// Boolean indicator to determine whether or not the modal should be open
isOpen: boolean;
// Helper function to open/close the modal */
setIsOpen: (isOpen: boolean) => void;
};
export const MFAModal = ({mfaMethods, isOpen, setIsOpen}: Props) => {
const {init, submit, cancel} = useMfa();
const [selectedMethod, setSelectedMethod] = useState<MfaMethod | null>(null);
const [mfaCode, setMfaCode] = useState('');
const [options, setOptions] = useState(null);
const [error, setError] = useState('');
const onMfaInit = async (method: MfaMethod) => {
const response = await init({method});
setError('');
setSelectedMethod(method);
if (method === 'passkey') {
setOptions(response);
}
};
const onMfaSubmit = async () => {
try {
if (selectedMethod === 'passkey') {
await submit({method: selectedMethod, mfaCode: options});
} else {
await submit({method: selectedMethod, mfaCode});
}
setSelectedMethod(null);
setIsOpen(false);
} catch (e) {
if (errorIndicatesMfaVerificationFailed(e)) {
setError('Incorrect MFA code, please try again.');
} else if (errorIndicatesMfaMaxAttempts(e)) {
setError('Maximum MFA attempts reached, please request a new code.');
setSelectedMethod(null);
} else if (errorIndicatesMfaTimeout(e)) {
setError('MFA code has expired, please request a new code.');
setSelectedMethod(null);
}
}
};
const onModalClose = () => {
cancel();
setIsOpen(false);
};
return (
<Modal visible={isOpen} animationType="slide" onRequestClose={onModalClose}>
<View style={{padding: 20}}>
{mfaMethods.map((method) => (
<Button
key={method}
title={`Choose to MFA with ${method}`}
onPress={() => onMfaInit(method)}
/>
))}
{selectedMethod && selectedMethod !== 'passkey' && (
<View>
<Text>Enter your MFA code below</Text>
<TextInput
placeholder="123456"
value={mfaCode}
onChangeText={setMfaCode}
keyboardType="numeric"
style={{borderBottomWidth: 1, marginBottom: 10}}
/>
<Button title="Submit Code" onPress={onMfaSubmit} />
</View>
)}
{error.length > 0 && <Text style={{color: 'red'}}>{error}</Text>}
<Button title="Close" onPress={onModalClose} />
</View>
</Modal>
);
};
Notice how the modal contains all logic for requesting the MFA code, submitting the MFA code, handling errors, and cancelling an in-progress MFA code.
Then, when your app needs to prompt a user to complete MFA, they can simply display this MFAModal
component and configure the mfaMethods
prop with the list of MFA methods that are available for the current user.
Registering an event listener
Once you've set up your app's logic for guiding a user to complete MFA, you lastly need to configure Privy to invoke this logic whenever MFA is required by the user's embedded wallet.
To set up this configuration, use Privy's useRegisterMfaListener
hook. As a parameter to useRegisterMfaListener
, you must pass a JSON object with an onMfaRequired
callback, described below.
onMfaRequired
Privy will invoke the onMfaRequired
callback you set whenever the user is required to complete MFA to use the embedded wallet. When this occurs, any use of the embedded wallet will be "paused" until the user has successfully completed MFA with Privy.
In this callback, you should invoke your app's logic for guiding through completing MFA (done via the useMfa
hook, as documented above). Within this callback, you can also access an mfaMethods
parameter that contains a list of available MFA methods that the user has enrolled in ('sms'
and/or 'totp'
and/or 'passkey'
).
Example registration
As an example, you might use the useRegisterMfaListener
within a component like below. This example uses the MFAModal
component implemented in the Prompting the user for MFA section of this guide.
tsx
import {useRegisterMfaListener, MfaMethod} from '@privy-io/expo';
import {MFAModal} from '../components/MFAModal';
export const MFAProvider = ({children}: {children: React.ReactNode}) => {
const [isMfaModalOpen, setIsMfaModelOpen] = useState(false);
const [mfaMethods, setMfaMethods] = useState<MfaMethod[]>([]);
useRegisterMfaListener({
// Privy will invoke this whenever the user is required to complete MFA
onMfaRequired: (methods) => {
// Update app's state with the list of available MFA methods for the user
setMfaMethods(methods);
// Open MFA modal to allow user to complete MFA
setIsMfaModalOpen(true);
},
});
return (
<View>
{/* This `MFAModal` component includes all logic for completing the MFA flow with Privy's `useMfa` hook */}
<MFAModal isOpen={isMfaModalOpen} setIsOpen={setIsMfaModalOpen} mfaMethods={mfaMethods} />
{children}
</View>
);
};
Handling errors with code submission
When both enrolling in and completing MFA, Privy sends a 6-digit code to the user's selected MFA method, that the user must submit to Privy in order to verify their identity. This is done via the following methods:
submitMfaEnrollment
from theuseMfaEnrollment
hook (for enrollment in SMS, TOTP, or passkey MFA)submit
from theuseMfa
hook (for completing MFA with SMS, TOTP, or passkey)
When submitting this MFA code, Privy may respond with an error if the code is incorrect, if the user has reached the maximum number of attempts for this MFA flow, or if the MFA flow has timed out. If the user enters in an incorrect code (e.g. by mistyping), the user is allowed to retry code submission up to a maximum of four attempts.
To simplify handling errors with MFA code submission, Privy provides the following helper functions to parse errors raised by the MFA code submission methods listed above. Each of these functions accepts the raw error
raised as a parameter, and returns a Boolean
indicating if the error meets a certain condition:
errorIndicatesMfaVerificationFailed
: indicates the user entered an incorrect MFA codeerrorIndicatesMfaMaxAttempts
indicates has reached the maximum number of attempts for this MFA flow, and that a new MFA code must be requested viainit
errorIndicatesMfaTimeout
indicates that the current MFA code has expired, and that a new MFA code must be requested viainit
As an example, to handle errors raised by submit
, you might use these helpers like so:
tsx
try {
// Errors from `submitEnrollmentWithSms` and `submitEnrollmentWithTotp` can be handled similarly
await submit({mfaCode: 'insert-mfa-code', method: 'insert-mfa-method'});
} catch (e) {
if (errorIndicatesMfaVerificationFailed(e)) {
console.error('Incorrect MFA code, please try again.');
// Allow the user to re-enter the code and call `submit` again
} else if (errorIndicatesMfaMaxAttempts(e)) {
console.error('Maximum MFA attempts reached, please request a new code.');
// Allow the user to request a new code with `init`
} else if (errorIndicatesMfaTimeout(e)) {
console.error('MFA code has expired, please request a new code.');
// Allow the user to request a new code with `init`
}
}