-
Notifications
You must be signed in to change notification settings - Fork 452
feat: Base MFA support #2480
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
feat: Base MFA support #2480
Changes from 9 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
877f488
feat: mfa error bubbling support
tusharpandey13 b59e97f
feat: add mfa example app and update docs
tusharpandey13 248eca7
Merge remote-tracking branch 'origin/main' into feat/mfa-base
tusharpandey13 d89cfa4
chore: fix example app
tusharpandey13 deb5bdb
chore: fix example app
tusharpandey13 c572c4a
chore: remove irrelevant code
tusharpandey13 0dbaffa
fix: use createHmac intead of createHash
tusharpandey13 ec0d87b
docs: add readme for mfa example app
tusharpandey13 742724a
chore: lint
tusharpandey13 e276681
feat: simplify mfa base implementation; move to a stateless design
tusharpandey13 dfb2467
chore: fix tests and lint
tusharpandey13 cfef8dd
chore: remove irrelevant code
tusharpandey13 6e1a368
Merge branch 'main' of https://github.com/auth0/nextjs-auth0 into fea…
tusharpandey13 4f35380
fix: correctly handle jwe decryption errors
tusharpandey13 ac7ec4d
chore: remove example app
tusharpandey13 e4e85d6
docs: fix docs
tusharpandey13 d633b3f
docs: fix docs
tusharpandey13 ee31989
docs: fix mfa action in examples
tusharpandey13 299ad79
docs: fix mfa action in examples
tusharpandey13 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| AUTH0_SECRET=use_a_long_random_string_here | ||
| APP_BASE_URL=http://localhost:3000 | ||
|
|
||
| AUTH0_ISSUER_BASE_URL='https://YOUR_DOMAIN.auth0.com' | ||
| AUTH0_DOMAIN=YOUR_DOMAIN.auth0.com | ||
| AUTH0_CLIENT_ID='YOUR_CLIENT_ID' | ||
| AUTH0_CLIENT_SECRET='YOUR_CLIENT_SECRET' | ||
| AUTH0_AUDIENCE='resource-server-1' | ||
| AUTH0_SCOPE='openid profile email offline_access' | ||
|
|
||
| # MFA Configuration | ||
| AUTH0_MFA_CONTEXT_TTL=300 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| # dependencies | ||
| /node_modules | ||
| /.pnp | ||
| .pnp.js | ||
|
|
||
| # testing | ||
| /coverage | ||
|
|
||
| # next.js | ||
| /.next/ | ||
| /out/ | ||
|
|
||
| # production | ||
| /build | ||
|
|
||
| # misc | ||
| .DS_Store | ||
| *.pem | ||
|
|
||
| # debug | ||
| npm-debug.log* | ||
| yarn-debug.log* | ||
| yarn-error.log* | ||
|
|
||
| # local env files | ||
| .env.local | ||
| !.env.local.example | ||
| .env.development.local | ||
| .env.test.local | ||
| .env.production.local | ||
|
|
||
| # vercel | ||
| .vercel |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| # Next.js MFA Step-up Authentication Example | ||
|
|
||
| This example demonstrates how to implement Step-up Authentication (MFA) for specific resources using `@auth0/nextjs-auth0` and Auth0 Actions. It handles the `mfa_required` error and ensures strict MFA enforcement without breaking standard session refreshes. | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| - An Auth0 Tenant. | ||
| - A basic understanding of [Auth0 Actions](https://auth0.com/docs/customize/actions). | ||
|
|
||
| ## ⚠️ Critical Configuration Warnings | ||
|
|
||
| 1. **Tenant MFA Policy**: Set your Global MFA Policy to **"Adaptive"** or **"Disabled"**. | ||
| * **Do NOT** use "Always" or "All Applications" globally. This enforces MFA on `refresh_token` exchanges (background updates), which will break your application's session management and cause infinite loops in Next.js. | ||
| 2. **Enforcement via Actions**: We use an Auth0 Action to enforce MFA only when specific conditions are met (e.g., requesting a specific Audience or Scope). | ||
|
|
||
| ## Setup Instructions | ||
|
|
||
| ### 1. Configure Auth0 Action | ||
|
|
||
| The "Gold Standard" for Step-up Authentication requires handling edge cases that standard documentation often overlooks. | ||
|
|
||
| Create a new **Post Login** Action in your Auth0 Dashboard with the following code. | ||
|
|
||
| **Why this code?** | ||
| * **Refresh Grant Guard**: `if (grantType === 'refresh_token') return;` is critical. Without it, silent token refreshes will fail. | ||
| * **Enrollment Check**: Checks if the user has factors enrolled before challenging. Calling `challengeWith` on an unenrolled user causes a 500 server error ("Something Went Wrong"). | ||
|
|
||
| ```javascript | ||
| /** | ||
| * Handler that will be called during the execution of a PostLogin flow. | ||
| * @param {Event} event - Details about the user and the context in which they are logging in. | ||
| * @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login. | ||
| */ | ||
| exports.onExecutePostLogin = async (event, api) => { | ||
| // 1. CRITICAL: Skip MFA for refresh token grants to prevent loops/errors in background updates | ||
| const grantType = event.request?.body?.grant_type; | ||
| if (grantType === 'refresh_token') { | ||
| return; | ||
| } | ||
|
|
||
| // 2. Define target (Audience or Scope) | ||
| // Adjust this to match the audience requested by your app | ||
| const targetAudience = event.secrets.TARGET_AUDIENCE || 'resource-server-1'; | ||
|
|
||
| const requestedAudience = event.transaction?.requested_audience || | ||
| event.request?.query?.audience || | ||
| (event.resource_server?.identifier); | ||
|
|
||
| // 3. Check if target is being requested | ||
| if (!requestedAudience || !requestedAudience.includes(targetAudience)) { | ||
| return; | ||
| } | ||
|
|
||
| // 4. Check if MFA already completed in this session | ||
| const authMethods = event.authentication?.methods || []; | ||
| const hasMfa = authMethods.some(method => method.name === 'mfa'); | ||
| if (hasMfa) { | ||
| return; | ||
| } | ||
|
|
||
| // 5. Check if user is enrolled | ||
| const enrolledFactors = event.user.multifactor || []; | ||
| if (enrolledFactors.length === 0) { | ||
| // Option: Force enrollment (api.authentication.enrollWith) or Fail | ||
| // For this test setup, we skip to avoid "Something went wrong" errors for new users | ||
| console.log('User has no MFA enrolled, skipping challenge'); | ||
| return; | ||
| } | ||
|
|
||
| // 6. Challenge | ||
| api.authentication.challengeWith({ type: 'otp' }); | ||
| }; | ||
| ``` | ||
|
|
||
| **Deploy the Action** and add it to your "Login" flow. | ||
|
|
||
| ### 2. Configure Environment Variables | ||
|
|
||
| Copy the example environment file and configure your Auth0 credentials. | ||
|
|
||
| ```bash | ||
| cp .env.local.example .env.local | ||
| ``` | ||
|
|
||
| Ensure your `AUTH0_ISSUER_BASE_URL`, `AUTH0_CLIENT_ID`, and `AUTH0_CLIENT_SECRET` are set. | ||
| For this example to work as intended, ensure your application requests the Audience defined in your Action logic (e.g., `AUTH0_AUDIENCE=resource-server-1`). | ||
|
|
||
| ### 3. Run the Application | ||
|
|
||
| ```bash | ||
| npm install | ||
| npm run dev | ||
| ``` | ||
|
|
||
| Visit `http://localhost:3000`. | ||
|
|
||
| ## How It Works | ||
|
|
||
| 1. **Initial Login**: The user logs in. If they don't request the sensitive scope/audience, no MFA is required. | ||
| 2. **Step-up Request**: When the user accesses a protected route or clicks a button that requests an Access Token for the sensitive audience: | ||
| * The SDK calls `getAccessToken`. | ||
| * Auth0 Action triggers and denies the token with `mfa_required`. | ||
| 3. **Error Handling**: | ||
| * The SDK catches the `MfaRequiredError`. | ||
| * The error object contains an `mfa_token`. | ||
| * The app redirects the user back to Auth0, passing this `mfa_token` to the `/authorize` endpoint. | ||
| 4. **Verification**: The user enters their OTP code. | ||
| 5. **Success**: Auth0 redirects back to the app with the step-up completed. The `getAccessToken` call now succeeds. | ||
|
|
||
| ## Troubleshooting & Common Pitfalls | ||
|
|
||
| - **"Something Went Wrong" on login**: The Action likely called `challengeWith` for a user who hasn't enrolled in MFA yet. Ensure your test user has enrolled manually (e.g., via Account Settings or a separate flow) before testing the step-up. The provided Action code defensively skips this challenge to prevent this error. | ||
| - **Endless interactions/Validation errors**: Check that your "Global Policy" in Auth0 is NOT set to "Always". It must be "Adaptive" or "Disabled" so the Action controls the logic. | ||
| - **Refresh Token fails**: Ensure the Action includes the `if (grantType === 'refresh_token') return;` check. Background requests for tokens must be allowed to proceed without interaction. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.