【问题标题】:Spring Test returning 401 for unsecured URLsSpring Test 为不安全的 URL 返回 401
【发布时间】:2017-01-26 00:41:01
【问题描述】:

我正在使用 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。

我是不是做错了什么?

【问题讨论】:

  • 请求是否在浏览器中使用相同的配置?
  • 是的,它确实有效
  • 闻起来像您的测试配置有问题。如果在 configure 中设置断点并调试测试会发生什么?
  • 抱歉,刚刚在文档中看到WebMvcTest注解只搜索WebMvcConfigurer而不搜索WebSecurityConfigurer
  • 您应该能够只使用@ContextConfiguration 来加载一个特定的配置器类。

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


【解决方案1】:

我找到了答案
Spring 文档说:

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

根据github中的这个问题:

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

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

因此,由于未选择 WebSecurityConfigurer 类,因此自动配置了默认安全性,这就是我在 url 中收到 401 而在我的安全配置中不受保护的动机。 Spring security 默认自动配置通过基本身份验证保护所有 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 都是我的配置类

【讨论】:

【解决方案2】:

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

@WebMvcTest(secure = false)

更多信息请访问javadocs

【讨论】:

  • 我使用的是 (at)AutoConfigureMockMvc 而不是 (at)WebMvcTest,但是为该注释提供 secure=false 解决了我从 MockMvc 发出的 401 响应,而我根本没有使用 Spring Security。
  • 唉,这对我不起作用。我得到一个 IllegalStateException。
  • 此属性自 2.1.0 起已弃用。
  • 在 spring boot 1.5.9 上,这根本没有帮助
【解决方案3】:

我遇到了一些问题,并在此处的答案和@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)));
  }
}

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

【讨论】:

    【解决方案4】:

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

     mockMvc.perform(get("/").with(httpBasic(username,rightPassword))
    

    【讨论】:

    • httpBasic() 在哪里找到?
    • @MattCampbell org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic
    猜你喜欢
    • 2016-10-16
    • 2021-11-18
    • 2020-10-03
    • 1970-01-01
    • 2019-02-01
    • 2013-09-10
    • 2017-04-26
    • 1970-01-01
    • 2021-06-06
    相关资源
    最近更新 更多