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);

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Why is it wrong? It works well, only not during testing, why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.