Skip to content

Fixing Re-authentication with passkeys#1

Open
everettbu wants to merge 2 commits into
improve-auth-user-experiencefrom
enhance-passkey-authentication-flow
Open

Fixing Re-authentication with passkeys#1
everettbu wants to merge 2 commits into
improve-auth-user-experiencefrom
enhance-passkey-authentication-flow

Conversation

@everettbu

@everettbu everettbu commented Jul 26, 2025

Copy link
Copy Markdown

Test 1

Summary by CodeRabbit

  • New Features

    • Enhanced support for passkey (WebAuthn) authentication during re-authentication flows, ensuring users can log in with passkeys even when prompted for re-authentication.
    • Improved handling and display of passkey options on the username and username-password forms based on realm configuration.
  • Bug Fixes

    • Resolved issues where passkey options were incorrectly hidden or shown during certain authentication and re-authentication scenarios.
  • Tests

    • Added comprehensive tests for passkey login and re-authentication flows, including cases with and without passkeys, and scenarios mixing password and passkey authentication.

mposolda and others added 2 commits July 22, 2025 10:00
closes #41242
closes #41008

Signed-off-by: mposolda <mposolda@gmail.com>
This change modifies the method signature to require a UserModel parameter
for proper user context validation during conditional passkey checks.
@coderabbitai

coderabbitai Bot commented Jul 26, 2025

Copy link
Copy Markdown

Walkthrough

This update refactors authentication logic around passkeys and re-authentication in the Keycloak authentication flow. It introduces utility methods for reauthentication error handling, encapsulates conditional passkey logic, and adds or updates several integration tests to verify passkey and re-authentication scenarios, including UI behavior and event assertions.

Changes

Cohort / File(s) Change Summary
Core Authenticator Logic Refactoring
services/src/main/java/org/keycloak/authentication/authenticators/browser/AbstractUsernameFormAuthenticator.java, .../UsernameForm.java, .../UsernamePasswordForm.java, .../WebAuthnAuthenticator.java, .../WebAuthnConditionalUIAuthenticator.java
Refactored authentication and re-authentication flows: centralized re-authentication error setup, encapsulated passkey and WebAuthn UI logic into helper methods, and updated control flow to respect conditional passkey settings.
Authenticator Utility Enhancement
services/src/main/java/org/keycloak/authentication/authenticators/util/AuthenticatorUtils.java
Added a static method to set up re-authentication error state in the username-password form, modifying form attributes based on session notes.
Passkeys and Re-authentication Integration Tests
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysOrganizationAuthenticationTest.java, .../PasskeysUsernameFormTest.java
Added new tests for verifying passkey login and re-authentication scenarios, including prompt=login behavior and event assertions. Adjusted existing tests to reflect updated UI expectations.
Comprehensive Passkeys/Password Test Enhancements
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysUsernamePasswordFormTest.java
Added multiple new test cases covering passkey and password login, re-authentication, negative scenarios, and UI checks. Refactored existing tests for clarity and coverage.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LoginForm
    participant Authenticator
    participant AuthUtils
    participant WebAuthn

    User->>LoginForm: Submit credentials
    LoginForm->>Authenticator: authenticate(context)
    alt User set & passkeys enabled
        Authenticator->>WebAuthn: fillContextForm(context)
        WebAuthn->>Authenticator: Return WebAuthn UI
    else User set & passkeys disabled
        Authenticator->>LoginForm: Skip username form
    end
    alt Error during re-authentication
        Authenticator->>AuthUtils: setupReauthenticationInUsernamePasswordFormError(context)
        AuthUtils->>LoginForm: Set USERNAME_HIDDEN, REGISTRATION_DISABLED
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

Hopping through the code with glee,
Passkeys and passwords in harmony!
Re-auth flows now neat and bright,
Tests ensure all works just right.
With whiskers twitching, I review anew—
Secure logins for every bunny and you!
🐇🔐✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 30f804a and 3214b18.

📒 Files selected for processing (9)
  • services/src/main/java/org/keycloak/authentication/authenticators/browser/AbstractUsernameFormAuthenticator.java (2 hunks)
  • services/src/main/java/org/keycloak/authentication/authenticators/browser/UsernameForm.java (1 hunks)
  • services/src/main/java/org/keycloak/authentication/authenticators/browser/UsernamePasswordForm.java (3 hunks)
  • services/src/main/java/org/keycloak/authentication/authenticators/browser/WebAuthnAuthenticator.java (2 hunks)
  • services/src/main/java/org/keycloak/authentication/authenticators/browser/WebAuthnConditionalUIAuthenticator.java (3 hunks)
  • services/src/main/java/org/keycloak/authentication/authenticators/util/AuthenticatorUtils.java (3 hunks)
  • testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysOrganizationAuthenticationTest.java (4 hunks)
  • testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysUsernameFormTest.java (2 hunks)
  • testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysUsernamePasswordFormTest.java (8 hunks)
🔇 Additional comments (27)
services/src/main/java/org/keycloak/authentication/authenticators/util/AuthenticatorUtils.java (3)

26-26: LGTM!

The import addition is necessary for the new utility method that uses LoginFormsProvider.


35-35: LGTM!

The static import allows direct use of the constant in the new utility method, improving readability.


124-133: Excellent refactoring to centralize re-authentication form setup.

This utility method effectively eliminates code duplication by centralizing the logic for configuring username/password forms during re-authentication errors. The implementation correctly:

  • Checks the authentication note to determine if the user was already set
  • Sets appropriate form attributes to hide username field and disable registration
  • Uses descriptive variable names and follows established patterns
services/src/main/java/org/keycloak/authentication/authenticators/browser/AbstractUsernameFormAuthenticator.java (2)

58-58: Appropriate visibility change to support centralized utility method.

Changing the constant from protected to public allows the new AuthenticatorUtils.setupReauthenticationInUsernamePasswordFormError method to access it, enabling code reuse across authenticators.


222-222: Excellent refactoring to use centralized utility method.

Replacing the inline form attribute setting with AuthenticatorUtils.setupReauthenticationInUsernamePasswordFormError(context) eliminates code duplication and centralizes the re-authentication error handling logic. This improves maintainability while preserving the original behavior.

services/src/main/java/org/keycloak/authentication/authenticators/browser/WebAuthnAuthenticator.java (2)

101-101: Good refactoring to improve extensibility.

Extracting the condition into a method call improves the design by allowing subclasses to override this behavior. The WebAuthnConditionalUIAuthenticator uses this to disable WebAuthn UI during conditional passkey flows.


124-130: Well-designed template method with clear documentation.

The new shouldShowWebAuthnAuthenticators method:

  • Preserves original behavior (returns true when user is present)
  • Provides clear JavaDoc explaining its purpose
  • Follows the Template Method pattern to allow subclass customization
  • Has appropriate protected visibility for inheritance
services/src/main/java/org/keycloak/authentication/authenticators/browser/UsernameForm.java (1)

47-47: Appropriate logic to handle conditional passkeys during re-authentication.

The additional !isConditionalPasskeysEnabled() condition correctly prevents skipping the username form when conditional passkeys are enabled. This ensures users can access passkey authentication options during re-authentication flows, improving the user experience for passkey-enabled scenarios.

services/src/main/java/org/keycloak/authentication/authenticators/browser/WebAuthnConditionalUIAuthenticator.java (3)

23-23: LGTM!

The import is necessary for the new utility method call in the createErrorResponse method.


53-53: Proper integration of centralized re-authentication error handling.

The call to AuthenticatorUtils.setupReauthenticationInUsernamePasswordFormError(context) ensures consistent form configuration during passkey authentication failures in re-authentication scenarios. This aligns with the broader refactoring effort to centralize this logic.


64-67: Appropriate override for conditional passkey UI behavior.

Overriding shouldShowWebAuthnAuthenticators to return false correctly disables the display of WebAuthn authenticators during conditional passkey flows (e.g., username/password login). The clear comment explains the purpose, and this behavior complements the parent class implementation.

services/src/main/java/org/keycloak/authentication/authenticators/browser/UsernamePasswordForm.java (3)

113-117: Good refactoring to centralize conditional logic

The extraction of the passkeys condition check into isConditionalPasskeysEnabled() improves code maintainability and consistency.


137-140: Consistent use of the helper method

Good consistency in using the same helper method for both authentication and challenge flows.


160-163: Confirm user null check is safe

I’ve verified that the new isConditionalPasskeysEnabled(context.getUser()) guard only affects the UI setup in UsernamePasswordForm and that all existing inline checks for webauthnAuth.isPasskeysEnabled()—including submission handling—remain unchanged. There are no code paths where the UI would now be gated without a user, so existing passkey flows before user lookup are intact.

testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysUsernameFormTest.java (2)

37-37: Required import for re-authentication test

The import is needed for the new re-authentication test that uses PROMPT_VALUE_LOGIN.


259-321: Well-structured re-authentication test

This test effectively validates that passkey authentication works during re-authentication flows (prompt=login). The test follows the established pattern and includes proper event verification.

testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysOrganizationAuthenticationTest.java (3)

35-35: Required import for re-authentication test

The import is needed for the new re-authentication test.


197-201: Updated assertions reflect correct WebAuthn UI behavior

The changes correctly assert that the WebAuthn form remains present even with non-discoverable keys, which aligns with the conditional passkeys feature behavior.

Also applies to: 211-211


268-321: Comprehensive re-authentication test coverage

This test provides good coverage for passkey re-authentication in the organization authentication context, following the same pattern as other re-authentication tests.

testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/webauthn/passwordless/PasskeysUsernamePasswordFormTest.java (8)

26-26: Necessary imports for enhanced test coverage

All added imports are required for the new test methods and assertions.

Also applies to: 35-35, 37-37, 41-41, 51-54


152-152: Improved null assertions

Good practice using Hamcrest's nullValue() matcher instead of direct null comparisons.

Also applies to: 165-165, 168-168


172-210: Well-structured test for external key authentication

This test properly validates authentication behavior with external (non-conditional UI) passkeys.


213-274: Comprehensive re-authentication test with external keys

Excellent test coverage for re-authentication flows with external passkeys, including proper info message validation.


277-333: Important negative test case

This test ensures passkeys UI elements are not shown when the feature is disabled, which is crucial for proper UI behavior.


336-422: Excellent mixed credential re-authentication test

This comprehensive test covers multiple scenarios including failed password attempts and successful authentication with both passkeys and passwords. The test properly validates that passkey UI remains available after failed password attempts.


424-431: Good refactoring with helper method

The helper method reduces code duplication across multiple tests that need the same passwordless policy configuration.


73-73: No missing definition – method inherited from test hierarchy
The call to configureTestRealm(realmRepresentation) comes from the superclass chain:

  • Declared abstract in AbstractTestRealmKeycloakTest
  • Implemented in AbstractChangeImportedUserPasswordsTest
    PasskeysUsernamePasswordFormTest (via AbstractWebAuthnVirtualTest) inherits this implementation. You can safely ignore this comment.

Likely an incorrect or invalid review comment.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch enhance-passkey-authentication-flow

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@everettbu

Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 29, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants