Raw
1 ---
2 sidebar_label: "Multi-Factor Authentication"
3 ---
4
5 import { Prerequisites } from "docs-ui"
6
7 export const metadata = {
8 title: `Multi-Factor Authentication`,
9 }
10
11 # {metadata.title}
12
13 In this guide, you'll learn how multi-factor authentication (MFA) works in the Auth Module, the providers it ships with, and how the authentication flow changes when an auth identity has MFA enabled.
14
15 <Prerequisites
16 items={[
17 {
18 text: "Medusa v2.15.5+",
19 link: "!docs!/learn/update"
20 }
21 ]}
22 />
23
24 ## What is Multi-Factor Authentication?
25
26 Multi-factor authentication adds a second verification step to the standard authentication flow. After a user authenticates with their credentials (such as email and password), they must pass another verification step using a second factor, such as a code from an authenticator app or a recovery code.
27
28 The Auth Module implements MFA around two concepts:
29
30 - **MFA factor**: A second factor enrolled for an auth identity, such as a TOTP authenticator. A factor is enabled only after the user verifies it once during setup.
31 - **MFA challenge**: A short-lived challenge issued during authentication. The user must verify the challenge with a registered MFA method to obtain a session token.
32
33 ---
34
35 ## Configure MFA Encryption Key
36
37 Medusa automatically configures MFA with sensible defaults, including setting the encryption key to the `AUTH_MFA_ENCRYPTION_KEY` environment variable. If you've created your application after v2.15.5 of Medusa, this key is generated for you and stored in the `.env` file.
38
39 If you created your application before v2.15.5, generate a random 64-character string and set it as the value of the `AUTH_MFA_ENCRYPTION_KEY` environment variable in your `.env` file:
40
41 ```bash
42 AUTH_MFA_ENCRYPTION_KEY=your_random_64_character_string
43 ```
44
45 You only need to explicitly configure MFA options in your `medusa-config.ts` if you want to override the defaults:
46
47 ```ts title="medusa-config.ts"
48 import { Modules, ContainerRegistrationKeys } from "@medusajs/framework/utils"
49
50 // ...
51
52 module.exports = defineConfig({
53 // ...
54 modules: [
55 {
56 resolve: "@medusajs/medusa/auth",
57 dependencies: [Modules.CACHE, ContainerRegistrationKeys.LOGGER],
58 options: {
59 mfa: {
60 encryption_key: process.env.AUTH_MFA_ENCRYPTION_KEY,
61 },
62 providers: [
63 {
64 resolve: "@medusajs/medusa/auth-emailpass",
65 id: "emailpass",
66 options: {
67 // provider options...
68 },
69 },
70 ],
71 },
72 },
73 ],
74 })
75 ```
76
77 If the `AUTH_MFA_ENCRYPTION_KEY` environment variable is not set and you haven't explicitly configured the `mfa.encryption_key` option, you'll get a "MFA encryption key is required to use MFA methods" error when trying to enroll or verify an MFA factor.
78
79 ---
80
81 ## MFA Providers
82
83 The Auth Module registers two MFA providers out of the box:
84
85 - `totp`: Time-based one-time password provider. Users enroll by scanning a QR code in an authenticator app (such as Google Authenticator or 1Password) and verify the factor with a six-digit code.
86 - `recovery_code`: Provides single-use backup codes that users can use to verify an MFA challenge when they don't have access to their primary factor.
87
88 The `recovery_code` provider is not enrolled as a factor on its own. It becomes available as a verification method once the user has at least one enabled MFA factor and generates recovery codes.
89
90 ### Custom MFA Providers
91
92 You can register custom MFA providers in the `mfa.providers` array of the Auth Module's options. These are either additional providers for custom usage, or providers that override the default `totp` and `recovery_code` providers.
93
94 For example, you can create a custom MFA provider that generates codes and sends them to the user via email or SMS. You can also override the default recovery code provider to customize the format of the generated codes or the way they're consumed.
95
96 To create a custom MFA provider, refer to the following guides:
97
98 - [Create a Custom MFA Provider](/references/auth/mfa-module-provider)
99 - [Create a Custom Recovery Code Provider](/references/auth/recovery-code-mfa-module-provider)
100
101 ---
102
103 ## Enrolling an MFA Factor
104
105 Enrolling an MFA factor means registering a second factor for an auth identity (such as a TOTP authenticator). Once the factor is enrolled and enabled, the user must verify with that factor during authentication.
106
107 The user enrolls an MFA factor by starting the enrollment, then verifying it.
108
109 ### Step 1: Authenticate with the Primary Factor
110
111 Before enrolling an MFA factor, the user must be authenticated with their primary factor (for example, by logging in with their email and password). This ensures that only authenticated users can enroll MFA factors for their account.
112
113 To authenticate, send a `POST` request to the `/auth/{actor_type}/{auth_provider}` API route with the user's credentials.
114
115 For example, to authenticate an admin user with their email and password, send a request to the login route:
116
117 ```bash
118 curl -X POST http://localhost:9000/auth/user/emailpass \
119 -H "Content-Type: application/json" \
120 -d '{
121 "email": "admin@example.com",
122 "password": "supersecret"
123 }'
124 ```
125
126 Use the returned JWT token in the `Authorization` header of subsequent requests to enroll and manage MFA factors.
127
128 ### Step 2: Start Enrollment
129
130 The client sends a `POST` request to `/auth/mfa/factors` to start enrollment for a specific provider:
131
132 ```bash
133 curl -X POST http://localhost:9000/auth/mfa/factors \
134 -H "Content-Type: application/json" \
135 -H "Authorization: Bearer {jwt_token}" \
136 -d '{
137 "provider": "totp",
138 "label": "Authenticator App",
139 "issuer": "My Store"
140 }'
141 ```
142
143 In the request body, you pass the following parameters:
144
145 - `provider`: The MFA provider to enroll (for example, `totp`).
146 - `label`: A label to identify the factor in the user's authenticator app.
147 - `issuer`: The name of your application or store, shown in the authenticator app.
148
149 The response contains the new factor in `pending` status, along with the data the user needs to register the factor in their authenticator app:
150
151 ```json title="Example Response"
152 {
153 "mfa_factor": { "id": "authmfa_...", "status": "pending", ... },
154 "secret": "JBSWY3DPEHPK3PXP",
155 "otpauth_url": "otpauth://totp/My%20Store:user@example.com?secret=..."
156 }
157 ```
158
159 For `totp` providers, the client typically renders `otpauth_url` as a QR code that the user scans with their authenticator app.
160
161 ### Step 3: Verify the Factor
162
163 Once the user has registered the factor in their authenticator app, the client sends the generated code to `/auth/mfa/factors/{id}/verify` to verify and activate the factor:
164
165 ```bash
166 curl -X POST http://localhost:9000/auth/mfa/factors/{id}/verify \
167 -H "Content-Type: application/json" \
168 -H "Authorization: Bearer {jwt_token}" \
169 -d '{
170 "code": "123456"
171 }'
172 ```
173
174 In the request body, you pass the `code` generated by the user's authenticator app.
175
176 On success, the factor's `status` becomes `enabled`, and the `auth.mfa_enabled` event is emitted. From now on, any authentication for this auth identity will require an MFA challenge.
177
178 ---
179
180 ## Authenticating with MFA
181
182 When an auth identity has at least one enabled MFA factor, the standard authentication flow returns an MFA challenge instead of an immediate session token.
183
184 Once the user successfully verifies the MFA challenge, they receive the session token and can access protected resources as usual.
185
186 ### Step 1: Authenticate with the Primary Factor
187
188 The user initiates authentication with their primary factor (for example, by logging in with their email and password):
189
190 ```bash
191 curl -X POST http://localhost:9000/auth/user/emailpass \
192 -H "Content-Type: application/json" \
193 -d '{
194 "email": "admin@example.com",
195 "password": "supersecret"
196 }'
197 ```
198
199 The response indicates that an MFA challenge is required:
200
201 ```json title="Example Response"
202 {
203 "mfa_challenge": {
204 "id": "authmfachal_...",
205 "methods": ["totp", "recovery_code"]
206 }
207 }
208 ```
209
210 The `methods` array lists the verification methods the user can complete to satisfy the challenge.
211
212 ### Step 2: Verify the Challenge
213
214 Based on the available methods, the client prompts the user to verify the challenge. For example, if `totp` is available, the user can enter the six-digit code from their authenticator app.
215
216 To verify the challenge, the client sends a `POST` request to `/auth/mfa/challenges/{id}/verify` with the chosen verification method and the corresponding code:
217
218 ```bash
219 curl -X POST http://localhost:9000/auth/mfa/challenges/{id}/verify \
220 -H "Content-Type: application/json" \
221 -d '{
222 "method": "totp",
223 "code": "123456"
224 }'
225 ```
226
227 On success, the response contains the JWT token the user can use in the `Authorization` header for subsequent requests:
228
229 ```json
230 {
231 "token": "..."
232 }
233 ```
234
235 Each challenge is single-use and expires after the configured TTL (default five minutes).
236
237 ---
238
239 ## Recovery Codes
240
241 Recovery codes give the user a way to verify an MFA challenge if they lose access to their primary factor.
242
243 ### Generating Recovery Codes
244
245 Once the user has at least one enabled MFA factor, they can generate recovery codes. First, they must be authenticated:
246
247 ```bash
248 curl -X POST http://localhost:9000/auth/user/emailpass \
249 -H "Content-Type: application/json" \
250 -d '{
251 "email": "admin@example.com",
252 "password": "supersecret"
253 }'
254 ```
255
256 Then, they can generate recovery codes using the `/auth/mfa/recovery-codes` route:
257
258 ```bash
259 curl -X POST http://localhost:9000/auth/mfa/recovery-codes \
260 -H "Content-Type: application/json" \
261 -H "Authorization: Bearer {jwt_token}" \
262 -d '{
263 "count": 10
264 }'
265 ```
266
267 In the request body, you can specify the number of recovery codes to generate. The default is either the `mfa.recovery_code_count` option from the Auth Module's configuration or `10`.
268
269 The response returns the generated codes in plain text:
270
271 ```json
272 {
273 "recovery_codes": ["abcd-efgh-ijkl", "..."]
274 }
275 ```
276
277 The user should store these codes in a safe place. The Auth Module stores only the hashed codes, so they cannot be retrieved again.
278
279 Generating a new set of recovery codes replaces the previous ones and emits the `auth.mfa_recovery_codes_generated` event.
280
281 ### Using a Recovery Code
282
283 To verify an MFA challenge with a recovery code, send a `POST` request to `/auth/mfa/challenges/{id}/verify` with `method` set to `recovery_code` and the `code` set to one of the valid recovery codes:
284
285 ```bash
286 curl -X POST http://localhost:9000/auth/mfa/challenges/{id}/verify \
287 -H "Content-Type: application/json" \
288 -d '{
289 "method": "recovery_code",
290 "code": "abcd-efgh-ijkl"
291 }'
292 ```
293
294 Each recovery code can be used only once. Once consumed, it cannot be reused for future challenges.
295
296 ---
297
298 ## Disabling an MFA Factor
299
300 To disable an enabled MFA factor, the client must be authenticated and send a `DELETE` request to `/auth/mfa/factors/{id}`:
301
302 ```bash
303 curl -X DELETE http://localhost:9000/auth/mfa/factors/{id} \
304 -H "Content-Type: application/json" \
305 -H "Authorization: Bearer {jwt_token}" \
306 -d '{
307 "method": "totp",
308 "code": "123456"
309 }'
310 ```
311
312 Whether the `method` and `code` fields are required depends on the value of the Auth Module's `disable_policy` option:
313
314 - `session` (default): A valid session is enough to disable the factor. The `method` and `code` fields are optional.
315 - `challenge`: The user must additionally verify with an MFA method (TOTP code or recovery code) before the factor can be disabled.
316
317 Use the `challenge` policy to protect users from a stolen session being used to remove their MFA factor.
318
319 On success, the factor's `status` becomes `disabled`, and the `auth.mfa_disabled` event is emitted.
320
321 ---
322
323 ## Listing Enrolled Factors
324
325 The client can list the MFA factors enrolled for the authenticated user by sending a `GET` request to `/auth/mfa/factors`:
326
327 ```bash
328 curl -X GET http://localhost:9000/auth/mfa/factors \
329 -H "Content-Type: application/json" \
330 -H "Authorization: Bearer {jwt_token}"
331 ```
332
333 The response includes each factor's `id`, `provider`, `status`, and metadata. Use this route to render the user's MFA settings page in your application.
334
335 ---
336
337 ## Require MFA on Custom API Routes
338
339 <Note>
340
341 This feature is available since [Medusa v2.20.0](https://github.com/medusajs/medusa/releases/tag/v2.20.0).
342
343 </Note>
344
345 By default, authenticated routes enforce MFA for any identity that has MFA enabled. You can customize this behavior when registering an `authenticate` middleware on your custom routes by passing the `requireMfa` option:
346
347 ```ts title="src/api/middlewares.ts"
348 import {
349 defineMiddlewares,
350 authenticate,
351 } from "@medusajs/framework/http"
352
353 export default defineMiddlewares({
354 routes: [
355 {
356 // Require MFA and that the challenge was completed within the last 5 minutes
357 matcher: "/admin/sensitive-action",
358 middlewares: [
359 authenticate("user", ["session", "bearer", "api-key"], {
360 requireMfa: { maxAgeSeconds: 300 },
361 }),
362 ],
363 },
364 {
365 // Explicitly disable the MFA requirement (e.g. for public or pre-MFA routes)
366 matcher: "/custom/public-route",
367 middlewares: [
368 authenticate("*", ["session", "bearer"], {
369 allowUnauthenticated: true,
370 requireMfa: false,
371 }),
372 ],
373 },
374 ],
375 })
376 ```
377
378 The `requireMfa` option accepts:
379
380 - `true` (default for authenticated routes): any request from an identity with MFA enabled must have a completed MFA challenge.
381 - `{ maxAgeSeconds: number }`: same as `true`, but also enforces that the challenge was completed within the given number of seconds. Use this to gate elevated actions (for example, changing a password or making a large payment) that require a recent MFA verification.
382 - `false`: skip MFA enforcement regardless of whether the identity has MFA enabled.
383
384 When `requireMfa` is not set, it defaults to `true` for routes that require authentication (`allowUnauthenticated: false`) and to `false` for routes that allow unauthenticated access.
385
386 Disabling MFA enforcement on a route is useful for routes that are part of the authentication flow (for example, login or MFA challenge verification) that require the user to be authenticated but not yet verified with MFA.
387
388 ---
389
390 ## Events
391
392 The Auth Module emits the following events around MFA:
393
394 - `auth.mfa_enabled`: Emitted when a factor transitions from `pending` to `enabled`.
395 - `auth.mfa_disabled`: Emitted when an enabled factor is disabled.
396 - `auth.mfa_recovery_codes_generated`: Emitted when a user generates a new set of recovery codes.
397
398 Subscribe to these events to send confirmation emails, audit log entries, or admin notifications.
399
400 Refer to the [Events Reference](/references/auth/events) for the full list of Auth Module events.