🔗 GitHub Repo: https://github.com/manueltechlabs/java-blog-project/tree/main

🔐 1. Introduction: Testing the Security of a Java-based blog and content management application

Security is an essential part of any web application. In this application, Spring Security manages authentication, authorization, password encoding, role hierarchies and access to protected resources.

However, configuring Spring Security correctly does not automatically guarantee that the application behaves as expected. We need to verify that the security rules work in practice, that users can authenticate with valid credentials, that unauthorized users are denied access and that application-specific authentication rules are respected.

For this purpose, I implemented two complementary testing approaches:

  • Unit testing: Tests individual security components independently, without starting the complete Spring application. For example, verifying that an administrator inherits lower-level roles and that BCrypt correctly encodes and matches passwords.
  • Integration testing: Tests how different parts of the application work together. In this particular application, this includes Spring Security, authentication services, HTTP requests, sessions and a real MySQL database provided by Testcontainers.

The implementation uses JUnit 5, Mockito, Spring Boot Test, MockMvc and Testcontainers.

An important distinction is that not every integration test needs a real database. Some tests use mocked services to isolate the security configuration, while others use actual persistence to verify the complete authentication process.

For example, the classSecurityConfigUnitTest verifies the role hierarchy, whereas AuthenticationIntegrationTest checks whether a registered account can authenticate against the database.

The objective is not simply to obtain a successful test report. It is to understand what each test verifies and gain confidence that the security implementation behaves as intended.

⚙️ 2. The Testing Environment and Dependencies

This testing environment uses Java 21, Spring Boot 3.2.5 and Maven. The tests are written with JUnit 5 and use the Spring testing framework to load application components and simulate HTTP requests.

The main dependencies are:

  • Spring Boot Starter Test: Provides JUnit 5.10.2, Mockito, AssertJ and Spring testing support.
  • Spring Security Test: Provides security-specific testing utilities, including @WithMockUser and CSRF request post-processors.
  • Testcontainers JUnit Jupiter: Integrates Testcontainers with JUnit 5.
  • Testcontainers MySQL: Provides the MySQL container implementation.
  • Spring Boot Testcontainers: Provides integration between Spring Boot and Testcontainers, including @ServiceConnection.
  • Testcontainers boom: Provides Testcontainers module versions.

The relevant Maven dependencies are:

Source: pom.xml

xml
1234567891011121314151617
      <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>mysql</artifactId>
    <scope>test</scope>
</dependency>
    

Testcontainers dependencies are managed through the Testcontainers BOM, which centralizes compatible dependency versions.

One detail worth noting in this project is the combination of Spring Boot 3.2.5 and Testcontainers 2.0.5. These are independently versioned projects. Their compatibility should be checked rather than assuming that importing the BOM guarantees compatibility with every Testcontainers integration. In particular, verify the availability and compatibility of the MySQL and JUnit Jupiter modules.

The tests also use the test Spring profile through @ActiveProfiles("test"). This allows test-specific configuration to be separated from production configuration, which becomes particularly important when introducing Docker-based database infrastructure and Docker secrets.

🧩 3. Unit Testing the Security Configuration

Before testing authentication through HTTP requests, I started by testing individual components of the security configuration.

These tests do not require a running Spring application context or a database. Instead, they instantiate SecurityConfig directly and invoke the methods responsible for creating the security-related beans.

The first test verifies the role hierarchy.

Source: SecurityConfigUnitTest.java

java
1234567891011121314
      @Test
void whenUserHasAdminRoleThenHasAllLowerRoles() {
    RoleHierarchy hierarchy = securityConfig.roleHierarchy();

    Collection<? extends GrantedAuthority> authorities =
        AuthorityUtils.createAuthorityList("ROLE_ADMIN");

    Collection<? extends GrantedAuthority> reachable =
        hierarchy.getReachableGrantedAuthorities(authorities);

    assertThat(reachable).extracting("authority")
        .contains("ROLE_ADMIN", "ROLE_EDITOR",
                  "ROLE_AUTHOR", "ROLE_SUBSCRIBER");
}
    

In SecurityConfig.java, the hierarchy is defined as follows:

java
123
      ROLE_ADMIN > ROLE_EDITOR
ROLE_EDITOR > ROLE_AUTHOR
ROLE_AUTHOR > ROLE_SUBSCRIBER
    

The test verifies that an administrator inherits all lower-level roles. This is important because the application uses hierarchical roles when determining user authorities.

The second test verifies password encoding.

Source: SecurityConfigUnitTest.java

java
123456789
      @Test
void whenEncodePasswordThenEncodedMatches() {
    PasswordEncoder encoder = securityConfig.passwordEncoder();

    String rawPassword = "password123";
    String encoded = encoder.encode(rawPassword);

    assertThat(encoder.matches(rawPassword, encoded)).isTrue();
}
    

The passwordEncoder() method in SecurityConfig.java returns a BCryptPasswordEncoder.

Rather than checking whether the encoded password equals a particular string, the test uses matches() to verify that the original password corresponds to its encoded representation.

BCrypt generates salted password hashes, so encoding the same password multiple times does not necessarily produce identical results.

Together, these tests establish that two fundamental security components work independently before moving on to integration testing.

🔗 4. Integration Testing with Spring Boot and MockMvc

Unit tests verify individual components, but they do not tell us whether the Spring application correctly connects those components. For this, I use integration testing with @SpringBootTest and @AutoConfigureMockMvc.

In This project, SecurityConfigIntegrationTest uses the following annotations:

Source: SecurityConfigIntegrationTest.java

java
12345678
      @SpringBootTest
@Testcontainers
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Import(SecurityConfig.class)
class SecurityConfigIntegrationTest {
    // Integration tests
}
    

Each annotation has a specific purpose:

  • @SpringBootTest loads the Spring application context, allowing the test to use the actual application configuration and dependency injection.
  • @AutoConfigureMockMvc configures MockMvc, which allows HTTP requests to be simulated without starting a real web server.
  • @ActiveProfiles("test") activates the test configuration.
  • @Testcontainers enables Testcontainers integration with JUnit Jupiter.
  • @Import(SecurityConfig.class) explicitly imports the security configuration.

The test also uses @ServiceConnection to connect Spring Boot to the MySQL container.

MockMvc is particularly useful for security testing because requests pass through the Spring MVC infrastructure and security filter chain. This allows us to verify authentication requirements, authorization rules, redirects and HTTP responses.

An important distinction is that MockMvc does not simulate an entire browser. It tests the server-side HTTP processing without requiring Selenium or Playwright.

In this implementation, I use Mockito’s @MockBean to replace selected application services and repositories. This allows the security configuration to be tested without requiring every business component to interact with a real database.

Consequently, this integration test focuses primarily on the security configuration, while the separate AuthenticationIntegrationTest verifies authentication using actual MySQL persistence.

🌐 5. Testing Public and Protected Endpoints

An important part of testing the security configuration is verifying that publicly accessible resources remain available while protected resources require authentication.

In SecurityConfig.java, I define which endpoints are publicly accessible and which require an authenticated user.

Source: SecurityConfig.java

java
123
      .requestMatchers("/", "/register", "/login").permitAll()
.requestMatchers("/profile/**").authenticated()
.requestMatchers("/admin/**").hasAuthority("ROLE_ADMIN")
    

The first integration test verifies that public pages and static resources are accessible without authentication.

Source: SecurityConfigIntegrationTest.java

java
1234567891011
      @Test
void whenRequestPublicPagesThenOk() throws Exception {
    mockMvc.perform(get("/"))
        .andExpect(status().isOk());

    mockMvc.perform(get("/login"))
        .andExpect(status().isOk());

    mockMvc.perform(get("/register"))
        .andExpect(status().isOk());
}
    

The next test verifies access to the profile page for an authenticated user.

java
12345678910
      @Test
@WithMockUser(
    username = "user@example.com",
    roles = {"SUBSCRIBER"}
)
void whenUserIsAuthenticatedThenCanAccessProfile()
        throws Exception {
    mockMvc.perform(get("/profile"))
        .andExpect(status().isOk());
}
    

@WithMockUser creates a simulated authenticated user in the Spring Security context. It does not perform an actual login or retrieve an account from the database.

For anonymous users, the expected behaviour is different:

java
12345678
      @Test
void whenUserIsAnonymousThenCannotAccessProfile()
        throws Exception {
    mockMvc.perform(get("/profile")
            .accept(MediaType.TEXT_HTML))
        .andExpect(status().is3xxRedirection())
        .andExpect(redirectedUrlPattern("**/login"));
}
    

Because the request is unauthenticated, Spring Security redirects the user to the login page.

These tests verify two fundamental security requirements: public resources must remain accessible, and protected resources must enforce authentication.

Although the configuration also restricts /admin/** to administrators, testing the complete role-based authorization behaviour is an additional improvement discussed later.

🔑 6. Testing the Form Login Flow

After verifying public and protected endpoints, the next step is testing the actual form login processing configured in Spring Security.

In this project, authentication is handled by Spring Security’s form login mechanism. The login form submits the user’s email and password to /login.

Source: SecurityConfig.java

java
12345678
      .formLogin(form -> form
    .loginPage("/login")
    .loginProcessingUrl("/login")
    .usernameParameter("email")
    .passwordParameter("password")
    .failureUrl("/login?error")
    .successHandler(myAuthenticationSuccessHandler)
    .permitAll())
    

The first test verifies successful authentication using a mocked UserDetailsService.

Source: SecurityConfigIntegrationTest.java

java
123456789101112131415161718
      @Test
void whenValidLoginThenRedirectsToHome() throws Exception {
    UserDetails user = User.builder()
        .username("admin@example.com")
        .password(passwordEncoder.encode("123"))
        .roles("ADMIN")
        .build();

    when(userDetailsService.loadUserByUsername(
        "admin@example.com")).thenReturn(user);

    mockMvc.perform(post("/login")
            .param("email", "admin@example.com")
            .param("password", "123")
            .with(csrf()))
        .andExpect(status().is3xxRedirection())
        .andExpect(redirectedUrl("/"));
}
    

Mockito configures the mocked service to return a valid user when Spring Security requests the account details. The password encoder is used to generate the expected BCrypt password.

The request includes .with(csrf()) because Spring Security enables CSRF protection by default. Without a valid CSRF token, the POST request would be rejected before authentication takes place.

The test also verifies that the custom AuthenticationSuccessHandler is invoked.

For unsuccessful authentication, the expected behaviour is a redirect to the error URL.

Source: SecurityConfigIntegrationTest.java

java
123456
      mockMvc.perform(post("/login")
        .param("email", "invalid@example.com")
        .param("password", "wrong")
        .with(csrf()))
    .andExpect(status().is3xxRedirection())
    .andExpect(redirectedUrl("/login?error"));
    

These tests verify the form login configuration and its HTTP responses.

One important limitation is that UserDetailsService is mocked here. Therefore, this test does not verify account retrieval, password persistence or disabled-account rules. Those are covered separately in AuthenticationIntegrationTest, where the actual application services and MySQL database are used.

🗄️ 7. Testing Authentication Against a Real MySQL Database

The previous integration tests use Mockito to isolate the security configuration from the application’s business services. However, successful authentication also depends on several components working together, including account persistence, password encoding, role retrieval and Spring Security’s UserDetailsService.

To verify this behaviour, I implemented a separate integration test called AuthenticationIntegrationTest.

Unlike SecurityConfigIntegrationTest, this test does not mock the account, password or role services. It uses the actual application services and a MySQL database started by Testcontainers.

Source: AuthenticationIntegrationTest.java

java
123456789101112131415
      @SpringBootTest
@Testcontainers
@AutoConfigureMockMvc
@ActiveProfiles("test")
@Transactional
class AuthenticationIntegrationTest {

    @Container
    @ServiceConnection
    static MySQLContainer<?> mysql =
        new MySQLContainer<>("mysql:8.0.39")
            .withDatabaseName("testdb")
            .withUsername("name")
            .withPassword("pwd");
}
    

@ServiceConnection allows Spring Boot to obtain the database connection details from the running container, avoiding the need to hardcode its connection URL.

Before each test, I create the required subscriber role, encode a password, create an account and persist it using the actual application services.

Source: AuthenticationIntegrationTest.java

java
123456
      Password password = new Password(
    passwordEncoder.encode(RAW_PASSWORD).toCharArray()
);

passwordService.save(password);
accountService.save(testAccount);
    

This setup ensures that authentication is tested against data stored in MySQL rather than objects returned by mocks.

The class also uses @Transactional. Each test runs within a transaction that is rolled back afterwards, helping prevent test data from interfering with subsequent tests.

This approach is particularly useful because it verifies the interaction between Spring Security, Hibernate, the repositories and the application’s service layer.

It also exposes problems that isolated unit tests cannot detect, such as incorrect entity mappings, database constraints and persistence errors.

✅ 8. Testing Authentication Business Rules

Having established the database integration, I can now test the authentication rules implemented in this application.

The first test verifies that a user with valid credentials can authenticate successfully.

Source: AuthenticationIntegrationTest.java

java
12345678910
      @Test
void whenValidCredentialsThenAuthenticationSucceeds()
        throws Exception {
    mockMvc.perform(post("/login")
            .with(csrf())
            .param("email", EMAIL)
            .param("password", RAW_PASSWORD))
        .andExpect(status().is3xxRedirection())
        .andExpect(redirectedUrl("/"));
}
    

After authentication, the test retrieves the account from the database and checks that lastLogin has been updated.

Other tests verify unsuccessful authentication scenarios:

  • Incorrect password: Authentication must fail when the password does not match the stored BCrypt hash.
  • Unknown email: An account that does not exist must not authenticate.
  • Disabled account: An account marked as disabled must be prevented from logging in.

The disabled-account rule is implemented in AccountServiceImpl.

Source: AccountServiceImpl.java

java
123
      if (account.isDisabled()) {
    throw new UsernameNotFoundException("Account disabled");
}
    

Spring Security treats this exception as an authentication failure.

Another important part of the implementation is the custom authentication success handler.

Source: LoginSuccessHandler.java

java
123
      String userName = authentication.getName();
accountService.updateLastLoginByEmail(userName);
response.sendRedirect("/");
    

This handler updates the last login timestamp after successful authentication and redirects the user to the home page.

The tests verify that lastLogin is populated after successful authentication but remains null after failed authentication.

Together, these tests demonstrate that authentication is not simply a matter of comparing passwords. It also involves enforcing account status rules and maintaining application-specific information about successful logins.

Note: PasswordServiceImpl is responsible for encoding passwords before persistence and matching submitted passwords against their stored hashes. This is another important part of the authentication process verified indirectly through the real login tests.

👤 9. Testing an Authenticated Session

Successful authentication is not the only behaviour that needs verification. Once a user has logged in, the application must maintain the authenticated state across subsequent HTTP requests.

In this application, I test this by performing an actual login through MockMvc, retrieving the resulting HTTP session and reusing it to access the protected profile page.

Source: AuthenticationIntegrationTest.java

java
12345678910
      MvcResult loginResult = mockMvc.perform(post("/login")
        .with(csrf())
        .param("email", EMAIL)
        .param("password", RAW_PASSWORD))
    .andExpect(status().is3xxRedirection())
    .andReturn();

MockHttpSession session =
    (MockHttpSession) loginResult.getRequest()
        .getSession(false);
    

The next step verifies that the session exists and uses it to access /profile.

java
1234
      assertThat(session).isNotNull();

mockMvc.perform(get("/profile").session(session))
    .andExpect(status().isOk());
    

This test is particularly important because it differs from using @WithMockUser.

With @WithMockUser, Spring Security creates a simulated authenticated user directly in the security context. No actual login takes place.

Here, Spring Security processes the submitted credentials, authenticates the account, establishes the session and associates the authenticated security context with it.

The subsequent request reuses that session, allowing us to verify that authentication is maintained between requests.

This gives us greater confidence that the login mechanism and session management work together correctly.

It also demonstrates how MockMvc can test stateful authentication without requiring a real browser or external HTTP client.

🐳 10. Testcontainers: Running MySQL for Integration Tests

For authentication integration tests, I need a real database. Mocking repositories would not verify whether Hibernate mappings, database constraints, relationships and persistence operations work correctly with MySQL.

Instead of installing and maintaining a separate MySQL instance for testing, I use Testcontainers.

Testcontainers is a Java library that starts disposable Docker containers for testing. In this project, I use its MySQL module to create an isolated database instance.

Source: AuthenticationIntegrationTest.java

java
1234567
      @Container
@ServiceConnection
static MySQLContainer<?> mysql =
    new MySQLContainer<>("mysql:8.0.39")
        .withDatabaseName("testdb")
        .withUsername("name")
        .withPassword("pwd");
    

Two annotations are particularly important:

  • @Container identifies the container managed by the Testcontainers JUnit integration.
  • @ServiceConnection allows Spring Boot to automatically obtain the connection details from the container.

Because the container is declared static, it is shared across test methods in the test class rather than restarted for every method.

The @Testcontainers annotation enables JUnit Jupiter integration and manages the container lifecycle.

This approach offers several advantages:

  • Isolation: Tests use a dedicated database rather than the production database.
  • Reproducibility: The specified MySQL image provides a consistent database version.
  • Automation: The database starts and stops as part of the test lifecycle.
  • Realistic integration: Hibernate and Spring Data JPA interact with an actual MySQL server.

One important consideration is that Testcontainers requires access to a Docker environment. This introduces additional configuration requirements when tests run inside another Docker container, which I will examine later.

For this project, Testcontainers provides a practical way to test authentication and persistence without manually managing a separate database installation.

🔄 11. Testcontainers versus DockerComposeContainer

Testcontainers offers different ways of managing the Docker containers required by integration tests. Two approaches are particularly relevant: individual container classes, such as MySQLContainer, and ComposeContainer, which uses a Docker Compose file to orchestrate multiple services.

These approaches are not mutually exclusive. They can coexist in the same project, even in different test classes, depending on what each test needs.

🐳 11.1. MySQLContainer: Individual containers

In this project, I use MySQLContainer because the authentication integration tests only require a MySQL database.

Source: AuthenticationIntegrationTest.java

java
1234567
      @Container
@ServiceConnection
static MySQLContainer<?> mysql =
    new MySQLContainer<>("mysql:8.0.39")
        .withDatabaseName("testdb")
        .withUsername("name")
        .withPassword("pwd");
    

This approach is straightforward and provides programmatic control over the database container.

🐳 11.2. ComposeContainer: Multiple services

ComposeContainer allows Testcontainers to start services defined in a Docker Compose file.

For example, a future integration test involving several cooperating services could use:

java
12345
      @Container
static ComposeContainer environment =
    new ComposeContainer(
        new File("src/test/resources/docker-compose-test.yml"))
        .withExposedService("database", 3306);
    

The example illustrates the approach; actual service configuration, networking and readiness checks must match the Compose file and Testcontainers version.

💡 11.3. Which approach should I use?

For this project, MySQLContainer is currently the simpler choice because the application needs only a database for these integration tests.

ComposeContainer becomes useful when testing interactions between several services, such as MySQL, message brokers and other applications.

Importantly, both approaches can be used in the same project. The decision depends on the infrastructure required by each test, not on a restriction imposed by Testcontainers.

Further information:

🔧 12. Docker Compose, Docker Socket and the Testing Environment

One of the challenges I encountered was running Testcontainers from inside a Docker container.

My docker-compose.yml defines a dedicated test service that runs Maven and mounts the host Docker socket:

Source: docker-compose.yml

yaml
123456789
      test:
  image: maven:3.9.8-eclipse-temurin-21
  volumes:
    - $PWD:$PWD
    - /var/run/docker.sock:/var/run/docker.sock
  working_dir: $PWD
  group_add:
    - "${DOCKER_GID}"
  command: mvn clean test
    

The Docker socket allows Testcontainers running inside the test container to communicate with the Docker daemon on the host. This is necessary because Testcontainers needs Docker to create and manage the MySQL container.

However, mounting the socket does not automatically guarantee that the test process has permission to access it.

🔍 12.1. Investigating Docker socket permissions

Initially, I encountered:

text
1
      Could not find a valid Docker environment.
    

After confirming that the socket was mounted, I investigated its permissions.

On the host, I obtained its group ID:

bash
1
      stat -c '%g' /var/run/docker.sock
    

The result was 990 in my environment.

I then passed that GID to Docker Compose:

bash
12
      export DOCKER_GID=$(stat -c '%g' /var/run/docker.sock)
docker compose --profile test up test
    

The group_add directive ensures that the test container process belongs to the group owning the socket.

🔑 12.2. Verifying permissions inside the container

I inspected the socket and process groups:

bash
12
      ls -l /var/run/docker.sock
id
    

My output included:

text
1
      srw-rw---- 1 root 990 ... /var/run/docker.sock
    

And:

text
1
      uid=0(root) gid=0(root) groups=0(root),990(990)
    

The message cannot find name for group ID 990 is not itself a permissions error. Linux determines group membership using numeric GIDs; the group does not need a name in /etc/group.

🔍 12.3. Investigating subordinate UID/GID mappings

I also investigated /etc/subuid and /etc/subgid:

bash
12
      grep "$USER" /etc/subuid
grep "$USER" /etc/subgid
    

These files define subordinate identity ranges used by user namespaces, particularly rootless Docker and user namespace remapping.

They are not universally required for Testcontainers. In my investigation, they were alternative areas to examine if ordinary socket permissions did not explain the problem.

The important distinction is that socket access, group membership and user namespace mappings are separate aspects of Docker security and configuration.

🛡️ 13. Security Implications of Mounting the Docker Socket

Although mounting /var/run/docker.sock solves the communication problem between Testcontainers and Docker, it introduces an important security risk.

The Docker socket provides access to the Docker daemon. A process with sufficient permissions to communicate with that daemon can create containers, mount host directories, inspect other containers and manage Docker resources.

In practice, access to an unrestricted Docker socket can provide root-equivalent control over the host. Therefore, running tests inside a container does not automatically isolate the host from potentially malicious test code.

This is particularly important in CI/CD environments where code may originate from external contributors or untrusted repositories.

🧩 13.1. Possible approaches

ApproachConsiderations
Docker socket mountingSimple, but grants substantial control over the host Docker daemon.
Docker-in-Docker (DinD)Uses a separate Docker daemon, but commonly requires privileged execution and careful isolation.
Testcontainers CloudOffloads container execution to an external managed environment, reducing the need for local Docker access.

None of these approaches is universally the best choice. Testcontainers Cloud is an alternative for test infrastructure, not a production deployment architecture.

🛡️ 13.2. Mitigating the risks

For this project, I would consider the following improvements when moving towards automated CI/CD:

  • Use dedicated CI runners rather than sharing a Docker daemon with unrelated workloads.
  • Only execute trusted code when Docker socket access is available.
  • Restrict access to the Docker socket and avoid mounting it into containers that do not need it.
  • Consider isolated Docker daemons or remote container execution.
  • Avoid exposing Docker access to untrusted pull requests.
  • Keep CI credentials and secrets separate from test container permissions.

The important lesson from this implementation is that Testcontainers simplifies database testing, but its Docker integration must be considered part of the security design.

A container is not necessarily a security boundary when it has access to the host Docker daemon. This is a particularly important consideration when transferring local testing practices into CI/CD pipelines.

🔒 14. Docker Secrets and Spring Test Configuration

In this project, I use Docker secrets to manage sensitive configuration values, such as database credentials and email account credentials.

Rather than hardcoding these values in docker-compose.yml, Docker mounts them as files inside the containers, normally under /run/secrets/.

For example, the production configuration references the secret files through environment variables.

Source: docker-compose.yml

yaml
1234
      environment:
  MYSQL_DATABASE: /run/secrets/mysql_database
  MYSQL_USER: /run/secrets/mysql_user
  MYSQL_PASSWORD: /run/secrets/mysql_password
    

This approach is part of my production configuration, where the application expects to obtain credentials through the mounted secret files.

⚙️ 14.1. Why this complicates testing

The difficulty arises because Testcontainers starts MySQL independently of the production Docker Compose environment.

When running tests, the production secret files might not exist inside the test container. Furthermore, Testcontainers provides its own database credentials, so the application must be configured to use those credentials rather than expecting production secret files.

In my application-test.properties, I therefore avoid relying on the production database connection settings.

properties
12
      spring.jpa.hibernate.ddl-auto=create-drop
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    

The @ServiceConnection annotation supplies the connection information from the MySQL container.

⚙️ 14.2. Separating production and test configuration

Using Spring profiles allows me to maintain different configurations for different environments:

  • Production: Uses Docker secrets for sensitive configuration.
  • Testing: Uses disposable database credentials supplied by Testcontainers.
  • Local development: Can use a separate configuration appropriate to the development environment.

An important distinction is that a Docker secret mounted as a file contains the secret value; the environment variable shown above contains the file path, not the actual credential.

I have documented the Docker secrets implementation separately, so I will not repeat its complete setup here.

The important point for this article is that introducing Testcontainers required adapting the testing configuration to work independently of the production secrets infrastructure, without weakening the production approach.

🚀 15. Additional Improvements and Future Work

The current implementation provides a good starting point for testing the security of this project. However, security testing should evolve alongside the application. There are several areas where additional tests would increase confidence in the implementation.

🔐 15.1. Additional Security Tests

Some useful improvements include:

  • CSRF protection: Verify that POST requests without a valid CSRF token are rejected.
  • Security headers: Check that the configured Content Security Policy and XSS protection headers are present in HTTP responses.
  • Role-based authorization: Test access to /admin/** with different roles, particularly ROLE_ADMIN and ROLE_EDITOR.
  • Privilege-based authorization: Test methods protected by @PreAuthorize or custom expressions using SecurityService.hasPrivilege().
  • Password reset: Test token generation, expiration, invalid tokens and successful password changes.
  • Logout and remember-me: These features are configured in SecurityConfig, but their behaviour still needs dedicated integration tests.

For example, CSRF protection can be tested in SecurityConfigIntegrationTest:

java
1234567
      @Test
void whenPostWithoutCsrf_thenForbidden() throws Exception {
    mockMvc.perform(post("/login")
            .param("email", "user@example.com")
            .param("password", "password123"))
        .andExpect(status().isForbidden());
}
    

⚙️ 15.2. Improving Test Maintainability

As the application grows, I would consider:

  • Separating security configuration tests from authentication business-rule tests.
  • Reusing test data creation methods to avoid duplicating account and role setup.
  • Using dedicated test profiles and properties to keep production configuration independent.
  • Reviewing database cleanup strategies and transaction boundaries.
  • Reducing unnecessary Spring application context initialisation to improve execution time.

The current use of @Transactional in AuthenticationIntegrationTest is useful for isolating database changes, but tests involving multiple transactions or asynchronous operations may require explicit cleanup strategies.

🗄️ 15.3. CI/CD Integration

An important next challenge is integrating these tests into a CI/CD pipeline.

The pipeline should automatically execute:

  • Unit tests using Maven.
  • Spring integration tests.
  • Testcontainers-based MySQL tests.
  • Test reports and failure summaries.

The CI environment must provide Docker access or an alternative supported container execution environment. This introduces security considerations, particularly when mounting /var/run/docker.sock. Dedicated runners, restricted repository access and appropriate secrets management are important safeguards.

A failed security test should cause the pipeline to fail rather than allowing an application with potentially broken authentication or authorization behaviour to proceed.

For this project, automating mvn clean verify would be a sensible starting point, provided the Maven lifecycle and test configuration are arranged to execute all the required tests.

Ultimately, these improvements would make the testing process more comprehensive, maintainable and suitable for automated software delivery.

🌍 16. Beyond This Article: End-to-End Browser Testing

The tests discussed in this article use MockMvc to simulate HTTP requests and verify Spring Security behaviour. However, MockMvc does not reproduce the complete browser experience.

As a future improvement, this project could benefit from end-to-end (E2E) testing using browser automation tools such as Selenium or Playwright.

These tools allow tests to interact with the application through a real browser, simulating user actions such as:

  • Entering credentials into the login form.
  • Navigating between public and protected pages.
  • Verifying session behaviour after authentication.
  • Testing form submissions, validation messages and redirects.
  • Checking that navigation and user interactions work as expected.

Selenium provides mature browser automation through WebDriver, while Playwright offers modern browser automation with support for multiple browser engines.

These approaches complement MockMvc rather than replace it. They provide another testing layer, helping verify that the security implementation works correctly from the user’s perspective.

🎯 17. Conclusion

Testing the security of this application has helped me understand why verifying authentication and authorization requires more than simply checking whether a user can log in.

The implementation combines three complementary testing approaches:

  • Unit testing: Verifies individual components of SecurityConfig, including role hierarchy and BCrypt password encoding, without starting the Spring application context or requiring a database.
  • Spring integration testing: Uses @SpringBootTest and MockMvc to verify HTTP security behaviour, public and protected endpoints, form login and authenticated sessions.
  • Testcontainers: Provides a real MySQL database for testing authentication against the application’s actual persistence layer, including account creation, password verification and disabled-account handling.

An important part of this implementation was also understanding how the testing environment interacts with Docker. Investigating the Docker socket permissions, numeric group IDs and container configuration helped identify infrastructure requirements that are easy to overlook when introducing Testcontainers.

There is still room for improvement, particularly in authorization testing, password-reset verification, CI/CD integration and browser-level testing.

The main objective is not simply to achieve a successful Maven build or increase the number of tests. It is to develop confidence that the security configuration and authentication mechanisms behave as expected in realistic conditions.

For this project, this is a starting point towards a more comprehensive and maintainable security testing strategy.