This is gonna be a tough one. I haven't yet been able to reproduce it reliably, although I have experienced it multiple times on different PCs.

Describe the bug Seemingly at random, our unit tests fail on a single test with the following error:

org.springframework.security.authentication.ProviderNotFoundException: No AuthenticationProvider found for org.springframework.security.authentication.TestingAuthenticationToken

When this error occurs, it always occurs on the host PC. That is, repeated executions of the failing test never pass. Strangely, the same failing test does pass on other PCs.

Even stranger, if I comment out the failing test and re-run all the tests in the project, a totally different test fails with the same error (a test that was passing in the previous execution).

Snippet of stack trace:

org.springframework.security.authentication.ProviderNotFoundException: No AuthenticationProvider found for org.springframework.security.authentication.TestingAuthenticationToken
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:251) ~[spring-security-core-5.3.5.RELEASE.jar:5.3.5.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.authenticateIfRequired(AbstractSecurityInterceptor.java:354) ~[spring-security-core-5.3.5.RELEASE.jar:5.3.5.RELEASE]
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:229) ~[spring-security-core-5.3.5.RELEASE.jar:5.3.5.RELEASE]
        ...truncated...

To Reproduce I have not yet been able to reliably reproduce the error. It has happened only twice in the last 4 months; once on a developer's Ubuntu workstation, and once on an Azure DevOps Ubuntu build agent. When it happened on our developer's workstation, we attempted to debug the test, which caused it to pass. It seems like delaying the test execution by setting a breakpoint somehow causes things to work.

Also, we've discovered that adding @WithAnonymousUser to the test somehow causes the failing test to pass.

Note that there is no security applied to this endpoint. All GET endpoints in this project are accessibly to unauthenticated users.

Expected behavior The tests execute the same on all platforms.

Sample As mentioned, I cannot reliably reproduce this issue. But here is the code that triggers the error:

@ActiveProfiles({ "test" })
@WebMvcTest({ GoalController.class })
@Import({ GoalModelAssembler.class })
class GoalControllerTest {

    @MockBean GoalService goalService;

    final GoalDto goal = ImmutableGoalDto.builder()
        .id(UUID.randomUUID().toString())
        .createdBy("resource-api")
        .description("Get jobs")
        .build();

    @Test
    void test() throws Exception {
        when(goalService.findAll(any(), any())).thenReturn(new PageImpl<>(singletonList(goal)));

        mockMvc.perform(get("/goals?fields=id,description"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$._embedded.goals", hasSize(1)))
            .andExpect(jsonPath("$._embedded.goals[0].id", is(goal.getId())))
            .andExpect(jsonPath("$._embedded.goals[0].description", is(goal.getDescription())))
            .andExpect(jsonPath("$._embedded.goals[0].createdBy").doesNotExist());
    }

}
@RestController
@RequestMapping({ "/goals" })
public class GoalController {

    private final GoalService goalService;

    private final GoalModelAssembler modelAssembler;

    private final ModelMapper mapper = Mappers.getMapper(ModelMapper.class);

    public GoalController(GoalService goalService, GoalModelAssembler modelAssembler) {
        this.goalService = goalService;
        this.modelAssembler = modelAssembler;
    }

    @GetMapping
    public CollectionModel<GoalResponseModel> readAll(GoalSearchModel searchCriteria, Pageable pageable, @RequestParam(defaultValue = "") List<String> fields) {
        final GoalDto goal = mapper.toDto(searchCriteria);
        return modelAssembler.toPagedModel(goalService.findAll(goal, pageable), fields);
    }

}

Comment From: eleftherias

@gregory-j-baker Based on the error message, it seems the test is using a TestingAuthenticationToken, however I don't see that in the code you shared. Do you have a different test that uses TestingAuthenticationToken? Your test environment might be polluted by a previous test.

One reason why tests fail intermittently is because of ordering. If the tests are not independent, then the order in which they are run may affect their outcome. Try swapping the test order to see if you can reproduce the error. You can use something like the JUnit @Order annotation try different orders.

Comment From: gregory-j-baker

The test that was failing does not use any TestingAuthenticationToken. The test class has 12 tests that all make unauthenticated GET requests to our controller. The tests are all very similar to the one that I pasted in my original comment. Also, there is no spring security at all in these tests anywhere.

Comment From: eleftherias

@gregory-j-baker Are you using XML configuration or Java configuration for security in your application? Do you have multiple XML files / Java classes that configure security? It could be a classpath scanning issue where the configurations are scanned in different orders depending on the machine.

Comment From: spring-projects-issues

If you would like us to look at this issue, please provide the requested information. If the information is not provided within the next 7 days this issue will be closed.

Comment From: spring-projects-issues

Closing due to lack of requested feedback. If you would like us to look at this issue, please provide the requested information and we will re-open the issue.