Spring Test为不安全的URL返回401

时间:2016-09-18 05:00:28

标签: java spring spring-mvc spring-boot spring-test

我正在使用Spring进行MVC测试

这是我的测试类

@RunWith(SpringRunner.class)
@WebMvcTest
public class ITIndexController {

    @Autowired
    WebApplicationContext context;

    MockMvc mockMvc;

    @MockBean
    UserRegistrationApplicationService userRegistrationApplicationService;

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

    @Test
    public void should_render_index() throws Exception {
        mockMvc.perform(get("/"))
            .andExpect(status().isOk())
            .andExpect(view().name("index"))
            .andExpect(content().string(containsString("Login")));
    }
}

这是MVC配置

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/login/form").setViewName("login");
    }
}

这是安全配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/resources/**", "/signup", "/signup/form", "/").permitAll()
            .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login/form").permitAll().loginProcessingUrl("/login").permitAll()
                .and()
            .logout().logoutSuccessUrl("/login/form?logout").permitAll()
                .and()
            .csrf().disable();
    }

    @Autowired
    public void configureGlobalFromDatabase(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }
}

当我运行测试时,它失败并显示消息:

java.lang.AssertionError: Status expected:<200> but was:<401>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:81)
at org.springframework.test.web.servlet.result.StatusResultMatchers$10.match(StatusResultMatchers.java:664)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
at com.marco.nutri.integration.web.controller.ITIndexController.should_render_index(ITIndexController.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

我知道它失败了,因为url受到spring安全保护,但是当我运行我的应用程序时,即使没有经过身份验证,我也可以访问该URL。

我做错了吗?

4 个答案:

答案 0 :(得分:13)

我找到答案了 Spring docs说:

  

@WebMvcTest将自动配置Spring MVC基础架构和   将扫描的bean限制为@ Controller,@ ControllerAdvice,@ JsonComponent,   Filter,WebMvcConfigurer和HandlerMethodArgumentResolver。定期   使用此批注时,不会扫描@Component bean。

根据github中的这个问题:

https://github.com/spring-projects/spring-boot/issues/5476

默认情况下@WebMvcTest会自动配置spring security,如果类路径中存在spring-security-test(在我的情况下是这样)。

因为没有选择WebSecurityConfigurer类,所以默认安全性是自动配置的,这就是我在我的安全配置中没有保护的url中接收401的动机。 Spring安全默认自动配置使用基本身份验证保护所有URL。

我解决问题的方法是使用@ContextConfiguration注释类,并在文档中描述@MockBean:

  

@WebMvcTest通常仅限于一个控制器并在其中使用   与@MockBean组合以提供模拟实现   需要合作者。

这是测试类

@RunWith(SpringRunner.class)
@WebMvcTest
@ContextConfiguration(classes={Application.class, MvcConfig.class, SecurityConfig.class})
public class ITIndex {

    @Autowired
    WebApplicationContext context;

    MockMvc mockMvc;

    @MockBean
    UserRegistrationApplicationService userRegistrationApplicationService;

    @MockBean
    UserDetailsService userDetailsService;

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

    @Test
    public void should_render_index() throws Exception {
        mockMvc.perform(get("/"))
            .andExpect(status().isOk())
            .andExpect(view().name("index"))
            .andExpect(content().string(containsString("Login")));
    }
}

Application,MvcConfig和SecurityConfig都是我的配置类

答案 1 :(得分:4)

不确定当问到原始问题时是否可用,但是如果真的不想测试Web请求的安全性部分(如果已知端点不安全,这似乎是合理的),那么我认为这可能是只需使用secure批注的@WebMvcTest属性即可完成操作(默认为true,因此将其设置为false会禁用Spring Security的MockMvc支持的自动配置):

@WebMvcTest(secure = false)

javadocs

中提供了更多信息

答案 2 :(得分:0)

如果您使用SpringJUnit4ClassRunner而不是SpringRunner,则可以在安全层中捕获您的请求。如果您使用的是基本身份验证,则必须在mockMvc.perform

中使用httpBasic方法
 mockMvc.perform(get("/").with(httpBasic(username,rightPassword))

答案 3 :(得分:0)

我遇到了一些问题,并通过此处的答案和@Sam Brannen评论来解决了该问题。

  

您可能不需要使用@ContextConfiguration。只需添加@Import(SecurityConfig.class)通常就足够了。

为了简化和更新答案,我想分享一下我如何在spring-boot2项目中修复它。

我要在端点以下进行测试。

@RestController
@Slf4j
public class SystemOptionController {

  private final SystemOptionService systemOptionService;
  private final SystemOptionMapper systemOptionMapper;

  public SystemOptionController(
      SystemOptionService systemOptionService, SystemOptionMapper systemOptionMapper) {
    this.systemOptionService = systemOptionService;
    this.systemOptionMapper = systemOptionMapper;
  }

  @PostMapping(value = "/systemoption")
  public SystemOptionDto create(@RequestBody SystemOptionRequest systemOptionRequest) {
    SystemOption systemOption =
        systemOptionService.save(
            systemOptionRequest.getOptionKey(), systemOptionRequest.getOptionValue());
    SystemOptionDto dto = systemOptionMapper.mapToSystemOptionDto(systemOption);
    return dto;
  }
}

所有服务方法必须是接口,否则无法初始化应用程序上下文。您可以检查我的SecurityConfig。

@Configuration
@EnableWebSecurity
@EnableResourceServer
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends ResourceServerConfigurerAdapter {

    @Autowired
    private ResourceServerTokenServices resourceServerTokenServices;

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        if (Application.isDev()) {
            http.csrf().disable().authorizeRequests().anyRequest().permitAll();
        } else {
            http
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .authorizeRequests().regexMatchers("/health").permitAll()
                .antMatchers("/prometheus").permitAll()
                .anyRequest().authenticated()
                    .and()
                    .authorizeRequests()
                    .anyRequest()
                    .permitAll();
            http.csrf().disable();
        }
    }

    @Override
    public void configure(final ResourceServerSecurityConfigurer resources) {
        resources.tokenServices(resourceServerTokenServices);
    }
}

在下面,您可以看到我的 SystemOptionControllerTest 类。

@RunWith(SpringRunner.class)
@WebMvcTest(value = SystemOptionController.class)
@Import(SecurityConfig.class)
public class SystemOptionControllerTest {

  @Autowired private ObjectMapper mapper;

  @MockBean private SystemOptionService systemOptionService;
  @MockBean private SystemOptionMapper systemOptionMapper;
  @MockBean private ResourceServerTokenServices resourceServerTokenServices;

  private static final String OPTION_KEY = "OPTION_KEY";
  private static final String OPTION_VALUE = "OPTION_VALUE";

  @Autowired private MockMvc mockMvc;

  @Test
  public void createSystemOptionIfParametersAreValid() throws Exception {
    // given

    SystemOption systemOption =
        SystemOption.builder().optionKey(OPTION_KEY).optionValue(OPTION_VALUE).build();

    SystemOptionDto systemOptionDto =
        SystemOptionDto.builder().optionKey(OPTION_KEY).optionValue(OPTION_VALUE).build();

    SystemOptionRequest systemOptionRequest = new SystemOptionRequest();
    systemOptionRequest.setOptionKey(OPTION_KEY);
    systemOptionRequest.setOptionValue(OPTION_VALUE);
    String json = mapper.writeValueAsString(systemOptionRequest);

    // when
    when(systemOptionService.save(
            systemOptionRequest.getOptionKey(), systemOptionRequest.getOptionValue()))
        .thenReturn(systemOption);
    when(systemOptionMapper.mapToSystemOptionDto(systemOption)).thenReturn(systemOptionDto);

    // then
    this.mockMvc
        .perform(
            post("/systemoption")
                .contentType(MediaType.APPLICATION_JSON)
                .content(json)
                .accept(MediaType.APPLICATION_JSON))
        .andDo(print())
        .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(content().string(containsString(OPTION_KEY)))
        .andExpect(content().string(containsString(OPTION_VALUE)));
  }
}

所以我只需要在我的mvc测试类中添加@Import(SecurityConfig.class)