Мой SecurityConfiguration
настроен следующим образом:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.authorizeRequests()
.antMatchers("/api/auth", "/api/auth/**", "/api/oauth2/**").permitAll()
.anyRequest().authenticated().and()
.oauth2Login()
//
}
Я проверяю свою пользовательскую аутентификацию POST конечные точки /api/auth/login
и /api/auth/register
. Приложение работает нормально, и в настоящее время я активно пишу юнит-тесты для них. В моем тестовом модуле контроллера у меня есть следующее:
@WebMvcTest(AuthenticationController.class)
@ContextConfiguration(classes = {AuthenticationController.class})
class AuthenticationControllerTest {
@Test
void register() throws Exception {
mockMvc.perform(post(BASE_PATH + "/register")
.content(...) // POST body
.with(csrf()))
.andExpect(status().isOk());
}
Это возвращает HTTP 401 (неавторизованный) вместо ожидаемого HTTP 200. Но если я добавлю @WithMockUser
(без каких-либо параметров) ) к методу тестирования, затем он возвращает 200. Зачем нужен поддельный пользователь, поскольку мне не требуется аутентификация на конечной точке /api/auth
? Конечно, я попытался установить /api/auth/**
в SecurityConfiguration
но та же проблема остается. Я еще не реализовал ничего, связанного с авторизацией, поэтому роли не являются проблемой.
РЕДАКТИРОВАТЬ: Стоит отметить, что я также попытался установить .anyRequest().permitAll()
, по сути говоря, что ни одна из моих конечных точек не требует аутентификации, но возникает та же проблема.
EDIT2: обновлен фрагмент теста, и я использую следующие зависимости:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>