繁体   English   中英

在 Spring 引导中与 OAuth2 一起使用时无法模拟 @PreAuthorize

[英]Cannot mock @PreAuthorize when using with OAuth2 in Spring Boot

我正在尝试为我的所有服务类编写单元测试,但我找不到关于如何在我的 controller 方法之上模拟@PreAuthorize的解决方案。 举个例子:

我在 controller 中有这个 function:

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

这在我的服务 class 中:

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

网络安全 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;
}

现在我正在尝试编写一个单元测试:

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

但我收到一个错误:

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

遗憾的是,spring-security 团队选择仅在测试框架中包含 MockMvc 请求后处理器和 WebTestClient 请求突变器,这限制了 OAuth2 身份验证 mocking 仅在控制器单元测试中。

希望我将测试注释的工作保留在我在 maven-central 上发布的一组库中: https://github.com/ch4mpy/spring-addons 您可以使用它测试任何@Component (示例取自此处):

@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 {
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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