Spring测试对于未经安全验证的URL返回401错误

31

我正在使用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 Security保护,但当我运行应用程序时,即使没有经过身份验证,我也可以访问该URL。

我做错了什么吗?


抱歉,刚在文档中看到WebMvcTest注释只搜索WebMvcConfigurer而不是WebSecurityConfigurer。 - Marco Prado
在这种情况下,我建议弄清楚应用安全配置需要什么配置,并编写一个自我答案。这是一个合理的问题,可能会发生在使用新的Boot测试功能的其他人身上。 - chrylis -cautiouslyoptimistic-
但是这仍然不合理,如果我的配置没有被选中,为什么URL返回401,就好像它是安全的?它应该返回OK。 - Marco Prado
我认为你应该在测试中更改这个:.andExpect(content().string(containsString("Login")));,而不是.andExpect(content().string(containsString("login"))); - Saurav Wahid
1
你应该可以直接使用@ContextConfiguration来加载那个特定的配置器类。 - chrylis -cautiouslyoptimistic-
显示剩余9条评论
6个回答

31

我找到了答案:
Spring文档说:

@WebMvcTest将自动配置Spring MVC基础设施, 并将扫描的bean限制为@Controller、@ControllerAdvice、@JsonComponent、 过滤器(Filter)、WebMvcConfigurer和HandlerMethodArgumentResolver。 使用此注释时,常规@Component bean将不被扫描。

根据github上的这个问题:

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

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

所以由于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 都是我的配置类。


13
通常情况下,您可能不需要使用@ContextConfiguration。只需添加@Import(SecurityConfig.class)通常就足够了。 - Sam Brannen
1
更多详情请参见:https://github.com/spring-projects/spring-boot/issues/6514 - Sam Brannen

11

不确定原问题提问时是否可用,但如果确实不想测试Web请求的安全部分(如果已知端点不安全,则似乎是合理的),那么我认为可以通过使用@WebMvcTest注释的secure属性来简单地完成此操作(它默认为true,因此将其设置为false应禁用Spring Security的MockMvc支持的自动配置):

@WebMvcTest(secure = false)

更多信息请参阅javadocs


我之前使用的是@AutoConfigureMockMvc而不是@WebMvcTest,但是在该注释中提供secure=false解决了我在MockMvc中遇到的401响应问题,因为我根本没有使用Spring Security。 - J E Carter II
唉,这对我没用。我得到了一个IllegalStateException异常。 - Matt Campbell
9
自2.1.0版本开始,此属性已被弃用。 - Chadi
3
在Spring Boot 1.5.9上,这并没有起到任何帮助作用。 - Dimitri Kopriwa

5

我曾遇到同样的问题,通过这里的答案和@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)

3

如果使用Spring Boot 2.0+,请尝试以下方法:

@WebMvcTest(controllers = TestController.class, excludeAutoConfiguration = {SecurityAutoConfiguration.class})


注:保留html标签,请勿写解释。

0
如果您使用SpringJUnit4ClassRunner而不是SpringRunner,您可以在安全层中捕获请求。如果您正在使用基本身份验证,则必须在mockMvc.perform内使用httpBasic方法。
 mockMvc.perform(get("/").with(httpBasic(username,rightPassword))

1
httpBasic() 在哪里找到? - Matt Campbell
@MattCampbell org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic - Ismoh

0
你可以添加这个 .header("apikey","apiValue");
如果你在资源中声明了这些值,那么你才能添加它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接