0

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);
edbras
  • 4,145
  • 9
  • 41
  • 78

1 Answers1

0

Your argument type is wrong, instead of Authentication you should use SecurityContext. The javadoc for the @CurrentSecurityContext says:

Annotation that is used to resolve the org.springframework.security.core.context.SecurityContext as a method argument.

Otherwise, if you just want the Authentication you don't need any annotation to resolve it. If you want the Principal of the authentication, you can use the @AuthenticatedPrincipal annotation.