Skip to content

πŸ›‘ Tests Failing with 401/403 after enabling Keycloak OAuth2 β€” disable or mock security in test profileΒ #1

@AdamNgazzou

Description

@AdamNgazzou

πŸ“‹ Description

After integrating Keycloak OAuth2 for service-to-service authentication, automated tests across several microservices (unit and slice/integration tests) now fail with HTTP 401/403 (Unauthorized / Access Denied). The security filter chain is active during test execution and blocks MockMvc and WebTestClient requests that previously succeeded.

πŸ› Reproduction

  1. Run mvn test (or execute CustomerControllerTest) on the local development machine.
  2. Observe controller tests returning 401/403 from MockMvc requests.

πŸ“ Actual vs. Expected

Category Actual Expected
Test Failures Tests fail due to authentication being enforced in the test context: Errors show unauthorized responses instead of exercising controller logic. Tests should either bypass authentication or simulate authenticated principals so controller and service logic can be validated without requiring real Keycloak tokens.
Scope Multiple services affected (customer, order, payment, product). N/A

πŸ’₯ Impact

  • Development: Slows local development and blocks merge requests because developers cannot run the full test suite reliably.
  • Quality Risk: Increases the chance of merging logic errors since developers cannot trust test results locally.

πŸ› οΈ Suggested Remediation (Pick one or combine)

  • Disable Globally: Add test configuration to disable security filters for test contexts (e.g., @AutoConfigureMockMvc(addFilters = false) or a test-only SecurityFilterChain bean that permits all).
  • Mock Per-Test: Use Spring Security test helpers for authenticated scenarios (e.g., @WithMockUser or SecurityMockServerConfigurers) for tests that assert security behavior.
  • Test Stub: Provide a lightweight test token validator/mocking layer or an in-memory Keycloak test stub for integration tests that need auth flows.

Please advise on the preferred approach (disable globally in tests, mock per-test, or provide a test auth stub) and I will produce the exact code patch for the selected option.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions