Подтвердить что ты не робот

Spring Проверка возврата 401 для необеспеченных URL-адресов

Я использую 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-адресу даже без проверки подлинности.

Я что-то делаю неправильно?

4b9b3361

Ответ 1

Я нашел ответ
Spring docs говорит, что:

@WebMvcTest будет автоматически настраивать инфраструктуру MVC Spring и ограничение отсканировано beans на @Controller, @ControllerAdvice, @JsonComponent, Фильтр, WebMvcConfigurer и HandlerMethodArgumentResolver. регулярное @Component beans не будет сканироваться при использовании этой аннотации.

И в соответствии с этой проблемой в github:

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

@WebMvcTest по умолчанию автоматически настраивает Spring безопасность, если spring -security-test присутствует в пути к классу (что в моем случае есть).

Итак, поскольку классы WebSecurityConfigurer не выбраны, система безопасности по умолчанию была настроена автоматически, то есть мотив, который я получал 401 в URL-адресе, который не был защищен в моей конфигурации безопасности. 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")));
    }
}

Приложение, MvcConfig и SecurityConfig - это все мои классы конфигурации

Ответ 2

Не уверен, что это было доступно, когда был задан исходный вопрос, но если действительно не требуется тестировать часть безопасности веб-запроса (что кажется разумным, если известно, что конечная точка небезопасна), то я думаю, что это можно сделать просто используя secure атрибут @WebMvcTest аннотации (он по умолчанию true так установить его в false следует отключить автоматическую конфигурацию поддержки MockMvc Spring Security):

@WebMvcTest(secure = false)

Более подробная информация доступна в Javadocs

Ответ 3

Если вы используете SpringJUnit4ClassRunner вместо SpringRunner, вы можете поймать свои запросы на уровне безопасности. Если вы используете базовую аутентификацию, вы должны использовать метод httpBasic для пользователя внутри mockMvc.perform

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

Ответ 4

У меня была какая-то проблема, и я решил ее с помощью ответов здесь и комментария @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.