Multi-Factor Authentication
note
Multi-Factor Authentication is in early access preview only. Although we believe it is production ready, APIs and some behavior may change based on feedback we receive in the preview period.
Multi-factor authentication (MFA), sometimes called two-factor authentication (2FA), adds an additional layer of security to your application by verifying their identity through additional verification steps.
It is considered a best practice to use MFA for your applications.
Users with weak passwords or compromised social login accounts are prone to malicious account takeovers. These can be prevented with MFA because they require the user to provide proof of both of these:
- Something they know. Password, or access to a social-login account.
- Something they have. Access to an authenticator app (a.k.a. TOTP), mobile phone or recovery code.
Overview#
Supabase Auth implements only Time-based One Time Factor(TOTP) multi-factor authentication. This type of multi-factor authentication uses a timed one-time password generated from an authenticator app in the control of users.
Applications using MFA require two important flows:
- Enrollment flow. This lets users set up and control MFA in your app.
- Authentication flow. This lets users sign in using any factors after the conventional login step.
Supabase Auth provides:
- Enrollment API - build rich user interfaces for adding and removing factors.
- Challenge and Verify APIs - securely verify that the user has access to a factor.
- List Factors API - build rich user interfaces for signing in with additional factors.
Below is a flow chart illustrating how these APIs work together to enable MFA features in your app.
These sets of APIs let you control the MFA experience that works for you. You can create flows where MFA is optional, mandatory for all or only specific groups of users.
Once users have enrolled or signed-in with a factor, Supabase Auth adds additional metadata to the user's access token (JWT) that your application can use to allow or deny access.
This information is represented by an Authenticator Assurance Level, a standard measure about the assurance Supabase Auth has of the user's identity for that particular session. There are two levels recognized today:
- Assurance Level 1:
aal1
Means that the user's identity was verified using a conventional login method such as email+password, magic link, one-time password, phone auth or social login. - Assurance Level 2:
aal2
Means that the user's identity was additionally verified using at least one second factor, such as a TOTP code.
This assurance level is encoded in the aal
claim in the JWT associated with
the user. By decoding this value you can create custom authorization rules in
your frontend, backend and database that will enforce the MFA policy that works
for your application. JWTs without an aal
claim are at the aal1
level.
Adding to your app#
Adding MFA to your app involves these three steps:
- Add enrollment flow. You need to provide a UI within your app that your users will be able to set-up MFA in. You can add this right after sign-up, or as part of a separate flow in the settings portion of your app.
- Add challenge step to login. If a user has set-up MFA, your app's login flow needs to present a challenge screen to the user asking them to prove they have access to the additional factor.
- Enforce rules for MFA logins. Once your users have a way to enroll and log in with MFA, you need to enforce authorization rules across your app: on the frontend, backend, API servers or Row-Level Security policies.
Add enrollment flow#
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:
- Right after login or sign up. This lets users quickly set up MFA immediately after they log in or create an account. We recommend encouraging all users to set up MFA if that makes sense for your application. Many applications offer this as an opt-in step in an effort to reduce onboarding friction.
- From within a settings page. Allows users to set up, disable or modify their MFA settings.
We recommend building one generic flow that you can reuse in both cases with minor modifications.
Enrolling a factor for use with MFA takes three steps:
- Call
supabase.auth.mfa.enroll()
. This method returns a QR code and a secret. Display the QR code to the user and ask them to scan it with their authenticator application. If they are unable to scan the QR code, show the secret in plain text which they can type or paste into their authenticator app. - Calling the
supabase.auth.mfa.challenge()
API. This prepares Supabase Auth to accept a verification code from the user and returns a challenge ID. - Calling the
supabase.auth.mfa.verify()
API. This verifies that the user has indeed added the secret from step (1) into their app and is working correctly. If the verification succeeds, the factor immediately becomes active for the user account. If not, you should repeat steps 2 and 3.
Example: React
Below is an example that creates a new EnrollMFA
component that illustrates
the important pieces of the MFA enrollment flow.
- When the component appears on screen, the
supabase.auth.mfa.enroll()
API is called once to start the process of enrolling a new factor for the current user. - This API returns a QR code in the SVG format, which is shown on screen using
a normal
<img>
tag by encoding the SVG as a data URL. - Once the user has scanned the QR code with their authenticator app, they
should enter the verification code within the
verifyCode
input field and click onEnable
. - A challenge is created using the
supabase.auth.mfa.challenge()
API and the code from the user is submitted for verification using thesupabase.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 theCancel
button.
1/**
2 * EnrollMFA shows a simple enrollment dialog. When shown on screen it calls
3 * the `enroll` API. Each time a user clicks the Enable button it calls the
4 * `challenge` and `verify` APIs to check if the code provided by the user is
5 * valid.
6 * When enrollment is successful, it calls `onEnrolled`. When the user clicks
7 * Cancel the `onCancelled` callback is called.
8 */
9export function EnrollMFA({
10 onEnrolled,
11 onCancelled,
12}: {
13 onEnrolled: () => void
14 onCancelled: () => void
15}) {
16 const [factorId, setFactorId] = useState('')
17 const [qr, setQR] = useState('') // holds the QR code image SVG
18 const [verifyCode, setVerifyCode] = useState('') // contains the code entered by the user
19 const [error, setError] = useState('') // holds an error message
20
21 const onEnableClicked = () => {
22 setError('')
23 ;(async () => {
24 const challenge = await supabase.auth.mfa.challenge({ factorId })
25 if (challenge.error) {
26 setError(challenge.error.message)
27 throw challenge.error
28 }
29
30 const challengeId = challenge.data.id
31
32 const verify = await supabase.auth.mfa.verify({
33 factorId,
34 challengeId,
35 code: verifyCode,
36 })
37 if (verify.error) {
38 setError(verify.error.message)
39 throw verify.error
40 }
41
42 onEnrolled()
43 })()
44 }
45
46 useEffect(() => {
47 ;(async () => {
48 const { data, error } = await supabase.auth.mfa.enroll({
49 factorType: 'totp',
50 })
51 if (error) {
52 throw error
53 }
54
55 setFactorId(data.id)
56
57 // Supabase Auth returns an SVG QR code which you can convert into a data
58 // URL that you can place in an <img> tag.
59 setQR(data.totp.qr_code)
60 })()
61 }, [])
62
63 return (
64 <>
65 {error && <div className="error">{error}</div>}
66 <img src={qr} />
67 <input
68 type="text"
69 value={verifyCode}
70 onChange={(e) => setVerifyCode(e.target.value.trim())}
71 />
72 <input type="button" value="Enable" onClick={onEnableClicked} />
73 <input type="button" value="Cancel" onClick={onCancelled} />
74 </>
75 )
76}
Add challenge step to login#
Once a user has logged in via their first factor (email+password, magic link, one time password, social login...) 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.) |
Example: React
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.
1function AppWithMFA() { 2 const [readyToShow, setReadyToShow] = useState(false) 3 const [showMFAScreen, setShowMFAScreen] = useState(false) 4 5 useEffect(() => { 6 ;(async () => { 7 try { 8 const { data, error } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel() 9 if (error) { 10 throw error 11 } 12 13 console.log(data) 14 15 if (data.nextLevel === 'aal2' && data.nextLevel !== data.currentLevel) { 16 setShowMFAScreen(true) 17 } 18 } finally { 19 setReadyToShow(true) 20 } 21 })() 22 }, []) 23 24 if (readyToShow) { 25 if (showMFAScreen) { 26 return <AuthMFA /> 27 } 28 29 return <App /> 30 } 31 32 return <></> 33}
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.- If the current level can be upgraded to the next one, the MFA screen is shown.
- Once the challenge is successful, the
App
component is finally rendered on screen.
Below is the component that implements the challenge and verify logic.
1function AuthMFA() {
2 const [verifyCode, setVerifyCode] = useState('')
3 const [error, setError] = useState('')
4
5 const onSubmitClicked = () => {
6 setError('')
7 ;(async () => {
8 const factors = await supabase.auth.mfa.listFactors()
9 if (factors.error) {
10 throw factors.error
11 }
12
13 const totpFactor = factors.data.totp[0]
14
15 if (!totpFactor) {
16 throw new Error('No TOTP factors found!')
17 }
18
19 const factorId = totpFactor.id
20
21 const challenge = await supabase.auth.mfa.challenge({ factorId })
22 if (challenge.error) {
23 setError(challenge.error.message)
24 throw challenge.error
25 }
26
27 const challengeId = challenge.data.id
28
29 const verify = await supabase.auth.mfa.verify({
30 factorId,
31 challengeId,
32 code: verifyCode,
33 })
34 if (verify.error) {
35 setError(verify.error.message)
36 throw verify.error
37 }
38 })()
39 }
40
41 return (
42 <>
43 <div>Please enter the code from your authenticator app.</div>
44 {error && <div className="error">{error}</div>}
45 <input
46 type="text"
47 value={verifyCode}
48 onChange={(e) => setVerifyCode(e.target.value.trim())}
49 />
50 <input type="button" value="Submit" onClick={onSubmitClicked} />
51 </>
52 )
53}
- You can extract the available MFA factors for the user by calling
supabase.auth.mfa.listFactors()
. Don't worry this method is also very quick and rarely uses the network. - If
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. - Each time the user presses the "Submit" button a new challenge is created for the chosen factor (in this case the first one) and it is immediately verified. Any errors are displayed to the user.
- On successful verification, the client library will refresh the session in
the background automatically and finally call the
onSuccess
callback, which will show the authenticatedApp
component on screen.
Enforce rules for MFA logins#
Adding MFA to your app's UI does not in-and-of-itself offer a higher level of security to your users. You also need to enforce the MFA rules in your application's database, APIs and server-side rendering.
Depending on your application's needs, there are three ways you can choose to enforce MFA.
- Enforce for all users (new and existing). Any user account will have to enroll MFA to continue using your app. The application will not allow access without going through MFA first.
- Enforce for new users only. Only new users will be forced to enroll MFA, while old users will be encouraged to do so. The application will not allow access for new users without going through MFA first.
- Enforce only for users that have opted-in. Users that want MFA can enroll in it and the application will not allow access without going through MFA first.
Database
Your app should sufficiently deny or allow access to tables or rows based on the user's current and possible authenticator levels.
caution
PostgreSQL has two types of policies: permissive and restrictive. This guide
uses restrictive policies. Make sure you don't omit the as restrictive
clause.
Enforce for all users (new and existing)
If your app falls under this case, this is a template Row Level Security policy you can apply to all your tables:
1create policy "Policy name."
2 on table_name
3 as restrictive
4 to authenticated
5 using (auth.jwt()->>'aal' = 'aal2');
- Here the policy will not accept any JWTs with an
aal
claim other thanaal2
, which is the highest authenticator assurance level. - Using
as restrictive
ensures this policy will restrict all commands on the table regardless of other policies!
Enforce for new users only
If your app falls under this case, the rules get more complex. User accounts
created past a certain timestamp must have a aal2
level to access the
database.
1create policy "Policy name."
2 on table_name
3 as restrictive -- very important!
4 to authenticated
5 using
6 (array[auth.jwt()->>'aal'] <@ (
7 select
8 case
9 when created_at >= '2022-12-12T00:00:00Z' then array['aal2']
10 else array['aal1', 'aal2', NULL]
11 end as aal
12 from auth.users
13 where auth.uid() = id));
- The policy will accept both
aal1
andaal2
for users with acreated_at
timestamp prior to 12th December 2022 at 00:00 UTC, but will only acceptaal2
for all other timestamps. - The
<@
operator is PostgreSQL's "contained in" operator. NULL
appears because some JWTs originating from prior to the introduction of MFA in Supabase Auth will not contain anaal
claim.- Using
as restrictive
ensures this policy will restrict all commands on the table regardless of other policies!
Enforce only for users that have opted-in
Users that have enrolled MFA on their account are expecting that your application only works for them if they've gone through MFA.
1create policy "Policy name."
2 on table_name
3 as restrictive -- very important!
4 to authenticated
5 using (
6 array[auth.jwt()->>'aal'] <@ (
7 select
8 case
9 when count(id) > 0 then array['aal2']
10 else array['aal1', 'aal2', NULL]
11 end as aal
12 from auth.mfa_factors
13 where auth.uid() = user_id and status = 'verified'
14 ));
- The policy will only accept only
aal2
when the user has at least one MFA factor verified. - Otherwise, it will accept both
aal1
andaal2
. - The
<@
operator is PostgreSQL's "contained in" operator. NULL
appears because some JWTs originating from prior to the introduction of MFA in Supabase Auth will not contain anaal
claim.- Using
as restrictive
ensures this policy will restrict all commands on the table regardless of other policies!
Server-Side Rendering#
tip
When using the Supabase JavaScript library in a server-side rendering context, make sure you always create a new object for each request! This will prevent you from accidentally rendering and serving content belonging to different users.
It is possible to enforce MFA on the Server-Side Rendering level. However, this can be tricky do to well.
You can use the supabase.auth.mfa.getAuthenticatorAssuranceLevel()
and
supabase.auth.mfa.listFactors()
APIs to identify the AAL level of the session
and any factors that are enabled for a user, similar to how you would use these
on the browser.
However, encountering a different AAL level on the server may not actually be a security problem. Consider these likely scenarios:
- User signed-in with a conventional method but closed their tab on the MFA flow.
- User forgot a tab open for a very long time. (This happens more often than you might imagine.)
- User has lost their authenticator device and is confused about the next steps.
We thus recommend you redirect users to a page where they can authenticate using their additional factor, instead of rendering a HTTP 401 Unauthorized or HTTP 403 Forbidden content.
APIs#
If your application uses the Supabase Database, Storage or Edge Functions, just using Row Level Security policies will give you sufficient protection. In the event that you have other APIs that you wish to protect, follow these general guidelines:
- Use a good JWT verification and parsing library for your language. This will let you securely parse JWTs and extract their claims.
- Retrieve the
aal
claim from the JWT and compare its value according to your needs. If you've encountered an AAL level that can be increased, ask the user to continue the login process instead of logging them out. - Use the
https://<project-ref>.supabase.co/rest/v1/auth/factors
REST endpoint to identify if the user has enrolled any MFA factors. Onlyverified
factors should be acted upon.
Frequently asked questions#
Why is there a challenge and verify API when challenge does not do much?#
TOTP is not going to be the only MFA factor Supabase Auth is going to support
in the future. By separating out the challenge and verify steps, we're making
the library forward compatible with new factors we may add in the future --
such as SMS or WebAuthn. For example, for SMS the challenge
endpoint would
actually send out the SMS with the authentication code.
What's inside the QR code?#
The TOTP QR code encodes a URI with the otpauth
scheme. It was initially
introduced by Google
Authenticator
but is now universally accepted by all authenticator apps.
How do I check when a user went through MFA?#
Access tokens issued by Supabase Auth contain an amr
(Authentication Methods
Reference) claim. It is an array of objects that indicate what authentication
methods the user has used so far.
For example, the following structure describes a user that first signed in with a password-based method, and then went through TOTP MFA 2 minutes and 12 seconds later. The entries are ordered most recent method first!
1{
2 "amr": [
3 {
4 "method": "mfa/totp",
5 "timestamp": 1666086056
6 },
7 {
8 "method": "password",
9 "timestamp": 1666085924
10 }
11 ]
12}
Use the supabase.auth.getAuthenticatorAssuranceLevel()
method to get easy
access to this information in your browser app.
You can use this PostgreSQL snippet in RLS policies, too:
1json_query_path(auth.jwt(), '$.amr[0]')
json_query_path(json, path)
is a function that allows access to elements in a JSON object according to a SQL/JSON path.$.amr[0]
is a SQL/JSON path expression that fetches the most recent authentication method in the JWT.
Once you have extracted the most recent entry in the array, you can compare the
method
and timestamp
to enforce stricter rules.
Currently recognized methods are:
password
- any password based sign in.otp
- any one-time password based sign in (email code, SMS code, magic link).oauth
- any OAuth based sign in (social login).mfa/totp
- a TOTP additional factor.
This list will expand in the future.