I am using the spring security annotation @CurrentSecurityContext to inject the authentication object. This works well when the application is running, but in a @SpringBootTest it always injects null, even when using @WithMockUser.
When adding breakpoints, the Authentication object in the SpringSecurityContext is correctly filled with a mock user principal, but the @CurrentSecurityContext resolver, namely: CurrentSecurityContextArgumentResolver is never used, it won't stop at any breakpoint (constructor, or resolver method) in this class.
I am using spring boot:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
And use mockMvc to perform a test:
@Test
@WithMockUser
void activate_NotActivatedYet() {
....
var result = mockMvc.perform(put(url).contentType(MediaType.APPLICATION_JSON)
.content(content)
.characterEncoding(CHAR_ENCODING))
.andDo(print())
.andDo(result -> flushIfNeeded())
.andDo(result -> entityManager.clear());
.....
}
And my rest endpoint:
@PutMapping("/{code}/activate")
public ResponseEntity<PromoCodeRestDto> activate(@CurrentSecurityContext Authentication authentication,
@PathVariable String code) {
log.info("Requesting to activate the promo code with code [{}]", code);