【问题标题】:Spring MVC - Error 404 with @EnableGlobalMethodSecurity when testing Controller using @WebMvcTestSpring MVC - 使用 @WebMvcTest 测试控制器时出现 @EnableGlobalMethodSecurity 错误 404
【发布时间】:2019-12-15 21:03:16
【问题描述】:

我们正在尝试将单元测试添加到我们的 Spring 项目 Controllers(顺便说一句,集成测试工作正常),但是当我们使用 @EnableGlobalMethodSecurity 添加配置时,我们遇到了一个非常奇怪的行为(使用 JSR-250注释)如果控制器实现了一个接口(无论接口)Controller 不包含在 Spring 应用程序上下文中作为“请求处理程序”(我在方法上检查了它:org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.processCandidateBean(String beanName)),即控制器中定义的请求映射(@PostMapping, ...) 没有注册为潜在位置,但是如果接口被移除,那么控制器和路径找到没有问题。

这是我的控制器(简化版),界面简单MyInterface

@RestController
@RequestMapping(path = "/api/customer")
@RolesAllowed({Role.Const.ADMIN})
public class CustomerController implements MyInterface {    
    @Override // The only method in MyInterface 
    public void myMethod(Object param) throws QOException {
        System.out.println("Hello");
    }    
    @PostMapping(path = {"/", ""})
    public Customer create(@RequestBody Customer data) throws QOException {
        return customerService.create(data);
    }
}

这是测试类(如果我删除 @EnableGlobalMethodSecurity 配置类一切正常):

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = CustomerController.class)
@Import({ CustomerController.class, TestAuthConfiguration.class, TestAuthConfiguration2.class})  //, TestAuthConfiguration.class })
@ActiveProfiles({"test", "unittest"})
@WithMockUser(username = "test", authorities = { Role.Const.ADMIN })
class CustomerControllerTest {
    private static final Logger LOG = LogManager.getLogger(CustomerControllerTest.class);
    @EnableWebSecurity
    protected static class TestAuthConfiguration extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            LOG.info("configure(HttpSecurity http) ");
            http.csrf().disable().authorizeRequests().filterSecurityInterceptorOncePerRequest(true)
                    .antMatchers("/api/session/**").permitAll() //
                    .antMatchers("/api/**").authenticated() //
                    .anyRequest().permitAll().and() //
                    .addFilterBefore(new OncePerRequestFilter() {
                        @Override
                        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                FilterChain filterChain) throws ServletException, IOException {
                            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                            if (auth != null) {
                                LOG.info("User authenticated: {}, roles: {}", auth.getName(), auth.getAuthorities());
                            }
                            filterChain.doFilter(request, response);
                        }
                    }, BasicAuthenticationFilter.class).sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }

    }

    @EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = false)
    protected static class TestAuthConfiguration2 extends GlobalMethodSecurityConfiguration {
        @Bean
        public GrantedAuthorityDefaults grantedAuthorityDefaults() {
            return new GrantedAuthorityDefaults(""); // Remove the ROLE_ prefix
        }
    }

    @Autowired
    MockMvc mockMvc;

    @Test
    void testCreate() throws Exception {
        Customer bean = new Customer();
        bean.setName("Test company");           
        when(customerServiceMock.create(bean)).thenReturn(bean);
        mockMvc.perform(post("/api/customer") 
        .content(JsonUtils.toJSON(bean)).contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("Test company"));
    }
}

我不明白发生了什么,我试图找到一个基于注释 JSR-250 (@RollesAllowed) 的具有安全性的控制器中的单元测试示例,但我没有发现任何有用的东西,无论如何这个问题听起来(对我来说)是一个错误,但我不确定,所以欢迎任何帮助。

库版本:

  • Spring Boot 版本:2.2.2
  • 弹簧核心:5.2.1
  • Mockito 核心:3.1.0

【问题讨论】:

  • 我遇到了类似的问题,并通过将 proxyTagerClass 添加为 true 以使其正常工作来解决它。 @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)

标签: java unit-testing spring-mvc-test springmockito jsr250


【解决方案1】:

尝试将proxyTargetClass 属性设置为true。我遇到了类似的问题,并通过添加这个来解决它。

@EnableGlobalMethodSecurity(jsr250Enabled = true, proxyTargetClass = true)

我还建议阅读 EnableGlobalMethodSecurity 的 javadocs,尤其要注意 proxyTargetClassmode 属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 2014-11-20
    • 2017-01-24
    相关资源
    最近更新 更多