Search code examples
angularspring-bootjunitspring-securityspring-framework-beans

Testing Method Security, how to test @PreAuthorize("#user.id != authentication.principal.id")?


I am trying to test a method in my UserController named update which looks like the following:

@RequestMapping(path = "/update", method = RequestMethod.PUT)
@PreAuthorize("#user.id != authentication.principal.id")
public ResponseEntity<User> update(@RequestBody final User user) {
    return new ResponseEntity<>(userService.saveElement(user), HttpStatus.OK);
}

but I can't seem to be able to access the id("#user.id != authentication.principal.id") in the test

When I remove the @PreAuthorize("#user.id != authentication.principal.id") the Test is green. I've tried adding

    @Test
    @WithMockUser(roles = {"ADMIN"}, id={"1"})
    ...
    }

or other modifiers too, but it didn't work

UserController.java

@Controller
@RequestMapping(API_PATH)
public class UserController {

    public static final String API_PATH = "/api/user";
    private final UserService userService;

    @Autowired
    public UserController(final UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(path = "/update", method = RequestMethod.PUT)
    @PreAuthorize("#user.id != authentication.principal.id")
    public ResponseEntity<User> update(@RequestBody final User user) {
        return new ResponseEntity<>(userService.saveElement(user), HttpStatus.OK);
    }
}

UserControllerTest.java

@ExtendWith(SpringExtension.class)
@SpringBootTest
@ContextConfiguration(classes = {TestContextConfiguration.class})
@WebAppConfiguration
class UserControllerTest {

    private MockMvc mvc;

    @Autowired
    private WebApplicationContext context;

    @MockBean
    private UserService userServiceMock;

    @BeforeEach
    void initTest() {
        MockitoAnnotations.initMocks(this);
        mvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build();
    }

    @Test
    @WithMockUser(roles = {"ADMIN"})
    void update() throws Exception {
        final String apiPath = UserController.API_PATH + "/update";
        final User user = new User();
        final String userAsJsonString = TestUtils.getObjectAsJsonString(user);

        mvc.perform(put(apiPath).contentType(MediaType.APPLICATION_JSON).content(userAsJsonString)).andExpect(status().isOk());

        Mockito.verify(userServiceMock).saveElement(ArgumentMatchers.any(User.class));
    }
}

Solution

  • with some help from friends, the problem is solved.

    One prblem was that I was trying to Test 2 Cases with one test and that the User I provided was Empty for the testMethod.

    Here is my solution:

        @Test
    @WithMockUser(roles = {"ADMIN"})
    void updateOwnAccount() throws Exception {
    
        final User user = TestUtils.createUser();
        user.setId(17);
    
        final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    
        mvc.perform(put(UserController.API_PATH + "/update").contentType(MediaType.APPLICATION_JSON).content(TestUtils.getObjectAsJsonString(user))).andExpect(
                status().isInternalServerError());
    }
    
    @Test
    @WithMockUser(roles = {"ADMIN"})
    void updateAnotherAccount() throws Exception {
    
        final User userToChange = TestUtils.createUser();
        userToChange.setId(17);
        final User userToLogin = TestUtils.createUser();
        userToLogin.setId(18);
    
        final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userToLogin, null, userToLogin.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    
        mvc.perform(put(UserController.API_PATH + "/update").contentType(MediaType.APPLICATION_JSON).content(TestUtils.getObjectAsJsonString(userToChange)))
                .andExpect(status().isOk());
    
        Mockito.verify(userServiceMock).saveElement(ArgumentMatchers.any(User.class));
    }