Thomas
Thomas

Reputation: 189

How to mock custom JWT claims in @WebMvcTest

I am using Spring Boot 2.2.0.RELEASE and my Spring-based backend acts as an OAuth2 Resource server which runs fine in production.

All my REST endpoints are protected :

public class BookingController {
 @PreAuthorize("hasAuthority('booking:WRITE')")
 @PostMapping(value = "/book")
 public ResponseEntity<Void> createBooking(@RequestBody BookModel bookModel, JwtAuthenticationToken jwt) {..}

I wanted to write a unit test against my REST APIs and I would like to mock the JWT token.

I tried the following but I always get the "Access denied message"

My Unit test looks like the following:

    @WebMvcTest(controllers = BookingController.class)
    public class BookingControllerTests {

     @Autowired
     private ObjectMapper objectMapper;

     @Autowired
     MockMvc mockMvc;

     @MockBean
     JwtDecoder jwtDecoder;

     @Test
     public void when_valid_booking_then_return_200() {
       BookModel bookModel = new BookModel();
       mockMvc
            .perform(post("/book")
            .with(jwt(jwt ->jwt().authorities(new SimpleGrantedAuthority("booking:WRITE"))))
            .contentType("application/json")
            .content(objectMapper.writeValueAsBytes(bookModel)))
            .andExpect(status().isCreated());
     }

Somehow the claims which are defined in mockMvc are ignored. See the debug output :

PrePostAnnotationSecurityMetadataSource : @org.springframework.security.access.prepost.PreAuthorize(value=hasAuthority('booking:WRITE')) found on specific method: public org.springframework.http.ResponseEntity BookingController.createBooking(BookModel ,org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) 

o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /book; Attributes: [permitAll]
o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken@eca97305: Principal: org.springframework.security.oauth2.jwt.Jwt@bbd01fb9; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: SCOPE_read
o.s.s.a.v.AffirmativeBased               : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@18907af2, returned: 1
o.s.s.w.a.i.FilterSecurityInterceptor    : Authorization successful
o.s.s.w.a.i.FilterSecurityInterceptor    : RunAsManager did not change Authentication object
o.s.s.w.FilterChainProxy                 : /book reached end of additional filter chain; proceeding with original chain
o.s.s.a.i.a.MethodSecurityInterceptor    : Secure object: ReflectiveMethodInvocation: public org.springframework.http.ResponseEntity BookingController.createBooking(BookModel,org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken); target is of class [BookModel]; Attributes: [[authorize: 'hasAuthority('booking:WRITE')', filter: 'null', filterTarget: 'null']]
o.s.s.a.i.a.MethodSecurityInterceptor    : Previously Authenticated: org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken@eca97305: Principal: org.springframework.security.oauth2.jwt.Jwt@bbd01fb9; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: SCOPE_read
o.s.s.a.v.AffirmativeBased               : Voter: org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter@67afe909, returned: -1
o.s.s.a.v.AffirmativeBased               : Voter: org.springframework.security.access.vote.RoleVoter@79f1e22e, returned: 0
o.s.s.a.v.AffirmativeBased               : Voter: org.springframework.security.access.vote.AuthenticatedVoter@6903ed0e, returned: 0
c.s.d.r.e.GlobalExceptionHandler         : mapped AccessDeniedException to FORBIDDEN

org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-5.2.0.RELEASE.jar:5.2.0.RELEASE]

Upvotes: 5

Views: 12729

Answers (3)

Akrem
Akrem

Reputation: 90

MvcResult result =
    mvc.perform(
            MockMvcRequestBuilders.get("/v1/path/example")
                .with(jwt(token -> token.claim("claimKey","claimValue"))
                .accept(MediaType.APPLICATION_JSON))
        .andReturn();

to use this you have to use mock mvc. so annotate your test class with @AutoConfigureMockMvc

and inject MockMvc

@Autowired private MockMvc mvc;

Upvotes: 0

In your lambda for mocking the JWT you are calling the post processor twice by using the parentheses twice .with(jwt(jwt ->jwt()...))

Instead, try

mockMvc
    .perform(post("/book")
    .with(jwt().authorities(new SimpleGrantedAuthority("booking:WRITE"))))

Upvotes: 9

geeksusma
geeksusma

Reputation: 314

If you need the security context up, then you are not writing an unit-test.

Anyway, why not to use @WithMockUser?

Here you can see a snapshot of how to use it in an Integration Test which is mocking the Business Layer.

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("api")
public class GetAllProfilesControllerITest {

@MockBean
private GetAllProfilesDAO getAllProfilesDAO;
@MockBean
private ProfileControllerMapper profileControllerMapper;

@Inject
private WebApplicationContext context;

private MockMvc mockMvc;

private static final String ENDPOINT = "/profiles";

@Before
public void setUp() {
    mockMvc = MockMvcBuilders.webAppContextSetup(context)
            .apply(springSecurity())
            .build();

}


@WithMockUser(authorities = "MINION")
@Test
public void should_returnUnauthorized_when_cantView() throws Exception {

    //when
    mockMvc.perform(get(ENDPOINT))
            //then
            .andExpect(status().isUnauthorized());

}

@WithMockUser(authorities = {"VIEW", "CREATE"})
@Test
public void should_returnOk_when_canView() throws Exception {

    //when
    mockMvc.perform(get(ENDPOINT))
            //then
            .andExpect(status().isOk());

}

@WithMockUser(authorities = "PUPPY")
@Test
public void should_returnOk_when_puppy() throws Exception {

    //when
    mockMvc.perform(get(ENDPOINT))
            //then
            .andExpect(status().isOk());

}

}

Upvotes: 0

Related Questions