简体   繁体   中英

Cannot mock @PreAuthorize when using with OAuth2 in Spring Boot

I am trying to write a Unit tests for all of my service classes, but I cannot find a solution on how to mock a @PreAuthorize above my controller methods. As an example:

I have this function in controller:

@GetMapping("/users")
@PreAuthorize("hasAuthority('ADMIN')")
public ResponseEntity<List<User>> getUsers() {
    return service.getUsers();
}

And this in my service class:

public ResponseEntity<List<User>> getUsers() {
    return new ResponseEntity<>(userRepository.findAll(), HttpStatus.OK);
}

WebSecurity class:

protected void configure(HttpSecurity http) throws Exception {
    http = http.cors().and().csrf().disable();
    http = http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and();
    http = http
            .exceptionHandling()
            .authenticationEntryPoint(
                    (request, response, ex) -> response.sendError(
                            HttpServletResponse.SC_UNAUTHORIZED,
                            ex.getMessage()
                    )
            )
            .and();

    http.authorizeRequests()
            .antMatchers(HttpMethod.GET, "/").permitAll()
            .anyRequest().authenticated();

    http.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwtAuthenticationConverter());
}

public JwtAuthenticationConverter jwtAuthenticationConverter() {
    JwtAuthenticationConverter converter = new JwtAuthenticationConverter();

    converter.setJwtGrantedAuthoritiesConverter(jwt ->
            Optional.ofNullable(jwt.getClaimAsStringList("permissions"))
                    .stream()
                    .flatMap(Collection::stream)
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList())
    );

    return converter;
}

Now I am trying to write a unit test this:

@Test
public void getAllUsers_shouldBeSuccess() throws Exception {
    ArrayList<User> users = new ArrayList<>();
    users.add(new User("0", true, new Role("USER")));

    when(userService.getUsers()).thenReturn(new ResponseEntity<>(users, HttpStatus.OK));

    mvc.perform(get("/users").with(jwt().jwt(jwt -> jwt.claim("permissions", "[ADMIN]"))))
            .andExpect(status().isOk())
            .andExpect(content().json(String.valueOf(users)));
}

But I receive an error:

java.lang.NoClassDefFoundError: `org/springframework/security/web/context/SecurityContextHolderFilter`

Sadly, spring-security team choosed to include in test framework MockMvc request post-processors and WebTestClient request mutators only, which limits OAuth2 authentication mocking in controllers unit-tests only.

Hopefully, I kept my work on test annotations in a set of libs I publish on maven-central: https://github.com/ch4mpy/spring-addons . You can test any @Component with it (sample taken from here ):

@Import(MessageServiceTests.TestConfig.class)
@ExtendWith(SpringExtension.class)
class MessageServiceTests {

    @Autowired
    private MessageService messageService;

    @Test()
    void greetWitoutAuthentication() {
        assertThrows(Exception.class, () -> messageService.getSecret());
    }

    @Test
    @WithMockJwtAuth(authorities = "ROLE_AUTHORIZED_PERSONNEL", claims = @OpenIdClaims(preferredUsername = "ch4mpy"))
    void greetWithMockJwtAuth() {
        final JwtAuthenticationToken auth = (JwtAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        assertThat(messageService.greet(auth)).isEqualTo("Hello ch4mpy! You are granted with [ROLE_AUTHORIZED_PERSONNEL].");
    }

    @TestConfiguration(proxyBeanMethods = false)
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    @Import({ MessageService.class })
    static class TestConfig {
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM