Skip to content

Commit 2595da6

Browse files
authored
Merge pull request #60 from devondragon/feature/mfa-challenge-ui
feat: Add MFA challenge UI pages and demo support
2 parents 18610cb + bcdc481 commit 2595da6

18 files changed

Lines changed: 746 additions & 5 deletions

File tree

‎.github/workflows/tests.yml‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
name: Tests
2+
3+
on:
4+
pull_request:
5+
push:
6+
branches: [main]
7+
8+
concurrency:
9+
group: tests-${{ github.workflow }}-${{ github.ref }}
10+
cancel-in-progress: true
11+
12+
jobs:
13+
unit-tests:
14+
name: Unit & Integration Tests
15+
runs-on: ubuntu-latest
16+
steps:
17+
- uses: actions/checkout@v4
18+
19+
- uses: actions/setup-java@v4
20+
with:
21+
distribution: temurin
22+
java-version: 21
23+
24+
- uses: gradle/actions/setup-gradle@v4
25+
26+
- name: Run tests
27+
run: ./gradlew test
28+
29+
- name: Upload test report
30+
if: failure()
31+
uses: actions/upload-artifact@v4
32+
with:
33+
name: gradle-test-report
34+
path: build/reports/tests/test/
35+
36+
playwright-tests:
37+
name: Playwright E2E Tests
38+
runs-on: ubuntu-latest
39+
services:
40+
mariadb:
41+
image: mariadb:12.2
42+
env:
43+
MARIADB_DATABASE: springuser
44+
MARIADB_USER: springuser
45+
MARIADB_PASSWORD: springuser
46+
MARIADB_ROOT_PASSWORD: rootpassword
47+
ports:
48+
- 3306:3306
49+
options: >-
50+
--health-cmd="healthcheck.sh --connect --innodb_initialized"
51+
--health-interval=10s
52+
--health-timeout=5s
53+
--health-retries=5
54+
env:
55+
# The MariaDB service container replaces Spring Boot's Docker Compose integration
56+
SPRING_DOCKER_COMPOSE_ENABLED: "false"
57+
steps:
58+
- uses: actions/checkout@v4
59+
60+
- uses: actions/setup-java@v4
61+
with:
62+
distribution: temurin
63+
java-version: 21
64+
65+
- uses: gradle/actions/setup-gradle@v4
66+
67+
- name: Build application
68+
run: ./gradlew assemble
69+
70+
- uses: actions/setup-node@v4
71+
with:
72+
node-version: 20
73+
cache: npm
74+
cache-dependency-path: playwright/package-lock.json
75+
76+
- name: Install Playwright dependencies
77+
working-directory: playwright
78+
run: |
79+
npm ci
80+
npx playwright install --with-deps chromium
81+
82+
- name: Run E2E tests (MFA disabled)
83+
working-directory: playwright
84+
env:
85+
APP_PROFILES: playwright-test
86+
run: npx playwright test --project=chromium
87+
88+
- name: Run E2E tests (MFA enabled)
89+
working-directory: playwright
90+
env:
91+
APP_PROFILES: playwright-test,mfa
92+
run: npx playwright test --project=chromium-mfa
93+
94+
- name: Upload Playwright report
95+
if: failure()
96+
uses: actions/upload-artifact@v4
97+
with:
98+
name: playwright-report
99+
path: playwright/reports/

‎CLAUDE.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,12 @@ This is a Spring Boot demo application showcasing the [Spring User Framework](ht
6262

6363
1. **No Custom User Entity**: This demo uses the framework's User entity directly. Custom user data goes in separate entities (like UserProfile).
6464

65-
2. **Configuration Profiles**:
65+
2. **Configuration Profiles**:
6666
- `local`: Development with local database
6767
- `test`: Integration testing with H2
6868
- `docker-keycloak`: OIDC integration with Keycloak
69+
- `registration-guard`: Enables domain-restricted registration (form/passwordless only)
70+
- `mfa`: Enables multi-factor authentication (PASSWORD + WEBAUTHN); combine with another profile, e.g. `local,mfa`
6971

7072
3. **Template Organization**: All Thymeleaf templates are in `src/main/resources/templates/` with subdirectories for user management (`email/`, `password/`, etc.)
7173

‎playwright/playwright.config.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,38 +84,55 @@ export default defineConfig({
8484
timeout: 10000,
8585
},
8686

87-
/* Configure projects for major browsers */
87+
/* Configure projects for major browsers.
88+
*
89+
* Tests tagged @mfa-enabled need the server running with the mfa profile and are excluded from
90+
* the default projects (whose specs assume MFA is off). Run them with:
91+
* APP_PROFILES=local,playwright-test,mfa npx playwright test --project=chromium-mfa
92+
*/
8893
projects: [
8994
{
9095
name: 'chromium',
96+
grepInvert: /@mfa-enabled/,
9197
use: { ...devices['Desktop Chrome'] },
9298
},
9399

94100
{
95101
name: 'firefox',
102+
grepInvert: /@mfa-enabled/,
96103
use: { ...devices['Desktop Firefox'] },
97104
},
98105

99106
{
100107
name: 'webkit',
108+
grepInvert: /@mfa-enabled/,
101109
use: { ...devices['Desktop Safari'] },
102110
},
103111

104112
/* Test against mobile viewports */
105113
{
106114
name: 'Mobile Chrome',
115+
grepInvert: /@mfa-enabled/,
107116
use: { ...devices['Pixel 5'] },
108117
},
109118

110119
{
111120
name: 'Mobile Safari',
121+
grepInvert: /@mfa-enabled/,
112122
use: { ...devices['iPhone 12'] },
113123
},
124+
125+
/* MFA flow tests: Chromium only (CDP virtual authenticator), MFA-enabled server required */
126+
{
127+
name: 'chromium-mfa',
128+
grep: /@mfa-enabled/,
129+
use: { ...devices['Desktop Chrome'] },
130+
},
114131
],
115132

116133
/* Run your local dev server before starting the tests */
117134
webServer: {
118-
command: 'cd .. && ./gradlew bootRun --args="--spring.profiles.active=local,playwright-test"',
135+
command: `cd .. && ./gradlew bootRun --args="--spring.profiles.active=${process.env.APP_PROFILES || 'local,playwright-test'}"`,
119136
url: 'http://localhost:8080',
120137
reuseExistingServer: !process.env.CI,
121138
timeout: 120000,
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import { test, expect, generateTestUser, createAndLoginUser } from '../../src/fixtures';
2+
3+
test.describe('MFA', () => {
4+
test.describe('Challenge Page', () => {
5+
test('should render the MFA WebAuthn challenge page structure', async ({
6+
page,
7+
testApiClient,
8+
cleanupEmails,
9+
}) => {
10+
// Login first so we have a session (page requires auth when MFA is disabled)
11+
const user = generateTestUser('mfa-page');
12+
cleanupEmails.push(user.email);
13+
14+
await createAndLoginUser(page, testApiClient, user);
15+
16+
// Navigate to the challenge page
17+
await page.goto('/user/mfa/webauthn-challenge.html');
18+
await page.waitForLoadState('domcontentloaded');
19+
20+
// Verify page structure
21+
await expect(page.locator('.card-header')).toContainText('Additional Verification Required');
22+
await expect(page.locator('#verifyPasskeyBtn')).toBeVisible();
23+
});
24+
25+
test('should have a cancel/sign out option', async ({
26+
page,
27+
testApiClient,
28+
cleanupEmails,
29+
}) => {
30+
const user = generateTestUser('mfa-cancel');
31+
cleanupEmails.push(user.email);
32+
33+
await createAndLoginUser(page, testApiClient, user);
34+
35+
await page.goto('/user/mfa/webauthn-challenge.html');
36+
await page.waitForLoadState('domcontentloaded');
37+
38+
// Verify cancel/sign out button is present (the navbar also has a logout
39+
// form, so target this button by its accessible name)
40+
await expect(
41+
page.getByRole('button', { name: 'Cancel and sign out' })
42+
).toBeVisible();
43+
});
44+
});
45+
46+
test.describe('MFA Status Endpoint', () => {
47+
test('should handle MFA status request for authenticated user', async ({
48+
page,
49+
testApiClient,
50+
cleanupEmails,
51+
}) => {
52+
const user = generateTestUser('mfa-status');
53+
cleanupEmails.push(user.email);
54+
55+
await createAndLoginUser(page, testApiClient, user);
56+
57+
// Call the MFA status endpoint
58+
const response = await page.request.get('/user/mfa/status');
59+
60+
// MFA is disabled in playwright-test profile, so endpoint returns 404.
61+
// A separate MFA-enabled test profile would be needed to test the 200 case.
62+
expect(response.status()).toBe(404);
63+
});
64+
65+
test('should not expose MFA status to unauthenticated requests', async ({ page }) => {
66+
// Call without authentication
67+
const response = await page.request.get('/user/mfa/status', {
68+
maxRedirects: 0,
69+
});
70+
71+
// With MFA disabled the endpoint is not in unprotectedURIs, so Spring
72+
// Security redirects unauthenticated requests to the login page.
73+
expect(response.status()).toBe(302);
74+
expect(response.headers()['location']).toContain('/user/login.html');
75+
});
76+
});
77+
});
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import { test, expect, generateTestUser, createAndLoginUser } from '../../src/fixtures';
2+
3+
/**
4+
* Full MFA flow E2E test using Chromium's CDP WebAuthn virtual authenticator.
5+
*
6+
* Requires the app to run with MFA enabled:
7+
* APP_PROFILES=local,playwright-test,mfa npx playwright test --project=chromium-mfa
8+
* (or start the server yourself with those profiles; the mfa profile must come last so its
9+
* overrides win).
10+
*
11+
* Tagged @mfa-enabled so the default projects skip it — their specs assume MFA is off.
12+
*/
13+
test.describe('MFA Full Flow @mfa-enabled', () => {
14+
test('password login requires passkey verification before reaching protected pages', async ({
15+
page,
16+
testApiClient,
17+
cleanupEmails,
18+
}) => {
19+
const user = generateTestUser('mfa-e2e');
20+
cleanupEmails.push(user.email);
21+
22+
// Set up a virtual authenticator before any WebAuthn ceremony. automaticPresenceSimulation
23+
// auto-approves create()/get() prompts so no human touch is needed.
24+
const cdp = await page.context().newCDPSession(page);
25+
await cdp.send('WebAuthn.enable');
26+
await cdp.send('WebAuthn.addVirtualAuthenticator', {
27+
options: {
28+
protocol: 'ctap2',
29+
transport: 'internal',
30+
hasResidentKey: true,
31+
hasUserVerification: true,
32+
isUserVerified: true,
33+
automaticPresenceSimulation: true,
34+
},
35+
});
36+
37+
// Password login leaves the user partially authenticated: PASSWORD satisfied, WEBAUTHN missing.
38+
await createAndLoginUser(page, testApiClient, user);
39+
40+
const partialStatus = await (await page.request.get('/user/mfa/status')).json();
41+
expect(partialStatus.data.satisfiedFactors).toContain('PASSWORD');
42+
expect(partialStatus.data.missingFactors).toContain('WEBAUTHN');
43+
expect(partialStatus.data.fullyAuthenticated).toBe(false);
44+
45+
// Any protected page redirects to the challenge page (and must not redirect-loop).
46+
await page.goto('/user/update-user.html');
47+
await expect(page).toHaveURL(/\/user\/mfa\/webauthn-challenge\.html/);
48+
await expect(page.locator('#verifyPasskeyBtn')).toBeVisible();
49+
50+
// Enroll the user's first passkey. The mfa profile unprotects the enrollment endpoints so a
51+
// partially-authenticated user can register; the virtual authenticator answers the ceremony.
52+
await page.evaluate(async () => {
53+
const { registerPasskey } = await import('/js/user/webauthn-register.js');
54+
await registerPasskey('e2e-virtual-passkey');
55+
});
56+
57+
// Complete the challenge with the freshly enrolled passkey.
58+
await page.locator('#verifyPasskeyBtn').click();
59+
await page.waitForURL((url) => !url.pathname.includes('webauthn-challenge'), {
60+
timeout: 15000,
61+
});
62+
63+
// Both factors satisfied now.
64+
const fullStatus = await (await page.request.get('/user/mfa/status')).json();
65+
expect(fullStatus.data.fullyAuthenticated).toBe(true);
66+
expect(fullStatus.data.missingFactors).toEqual([]);
67+
68+
// Protected pages are reachable again.
69+
await page.goto('/user/update-user.html');
70+
await expect(page).toHaveURL(/\/user\/update-user\.html/);
71+
72+
// And the profile page renders the MFA badges from the status endpoint's data envelope.
73+
const badges = page.locator('#mfaStatusBadges');
74+
await expect(badges).toContainText('MFA Active');
75+
await expect(badges).toContainText('Fully Authenticated');
76+
await expect(badges).not.toContainText('Additional Factor Required');
77+
});
78+
});
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.digitalsanctuary.spring.demo.config;
2+
3+
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.security.config.annotation.authorization.EnableMultiFactorAuthentication;
6+
7+
/**
8+
* Enables Spring Security 7's MFA filter support when {@code user.mfa.enabled=true}.
9+
*
10+
* <p>
11+
* {@code @EnableMultiFactorAuthentication} registers a {@code BeanPostProcessor} that sets {@code mfaEnabled} on the
12+
* authentication filters. With it, a second login in the same session (e.g. a WebAuthn assertion after a password
13+
* login) <em>merges</em> the new authentication's authorities with the current ones, accumulating
14+
* {@code FactorGrantedAuthority}s. Without it, the passkey verification <em>replaces</em> the session authentication,
15+
* dropping the PASSWORD factor — the user can then never satisfy both factors and bounces between the two challenge
16+
* pages forever.
17+
* </p>
18+
*
19+
* <p>
20+
* The {@code authorities} attribute is left empty on purpose: the Spring User Framework already configures the
21+
* required-factor authorization rules from the {@code user.mfa.factors} property.
22+
* </p>
23+
*/
24+
@Configuration
25+
@ConditionalOnProperty(name = "user.mfa.enabled", havingValue = "true", matchIfMissing = false)
26+
@EnableMultiFactorAuthentication(authorities = {})
27+
public class MfaSecurityConfig {
28+
}

‎src/main/java/com/digitalsanctuary/spring/demo/controller/PageController.java‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,5 +51,14 @@ public String terms() {
5151
return "terms";
5252
}
5353

54+
/**
55+
* MFA WebAuthn Challenge Page.
56+
*
57+
* @return the path to the MFA WebAuthn challenge page
58+
*/
59+
@GetMapping("/user/mfa/webauthn-challenge.html")
60+
public String mfaWebAuthnChallenge() {
61+
return "user/mfa/webauthn-challenge";
62+
}
5463

5564
}

0 commit comments

Comments
 (0)