Spring Boot 4/Spring Security 6 – @WithMockUser возвращает 401 Несанкционировано в тесте MockMvcJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Spring Boot 4/Spring Security 6 – @WithMockUser возвращает 401 Несанкционировано в тесте MockMvc

Сообщение Anonymous »

Я настраиваю проект с использованием Spring Boot 4.0.2 (Spring Security 6) и получаю сообщение 401 Unauthorized в интеграционном тесте MockMvc, хотя я использую @WithMockUser(roles = "ADMIN").
Я подозреваю, что это может быть связано с изменениями в пакетах Spring Security или конфигурации теста в сравнении на Spring Boot 3x, но не могу понять, в чем дело.
Конфигурация безопасности

Код: Выделить всё

@Configuration
public class ProjectConfig {

@Bean
UserDetailsService userDetailsService() {
var user = User.withUsername("john")
.password("{noop}password")
.roles("USER")
.build();

var admin = User.withUsername("admin")
.password("{noop}admin")
.roles("ADMIN")
.build();

return new InMemoryUserDetailsManager(user, admin);
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.POST, "/api/v1/products").hasRole("ADMIN")
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable);

return http.build();
}
}
Контроллер

Код: Выделить всё

@RestController
@RequestMapping("/api/v1/products")
@RequiredArgsConstructor
public class ProductController {

private final ProductService productService;

@PostMapping
public ResponseEntity
  createProduct(@RequestBody Product product) {
return new ResponseEntity(
productService.createProduct(product),
HttpStatus.CREATED
);
}
}

Интеграционный тест

Код: Выделить всё

import com.francislainy.ecomproductservice.TestcontainersConfiguration;
import com.francislainy.ecomproductservice.service.impl.ProjectConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.context.annotation.Import;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@Import({TestcontainersConfiguration.class, ProjectConfig.class})
public class ProductIT {

@Autowired
MockMvc mockMvc;

@WithMockUser(roles = {"ADMIN"})
@Test
void shouldCreateProductWhenAdmin() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/products")
.contentType(MediaType.APPLICATION_JSON)
.content("{}"))
.andExpect(status().isCreated());
}

}
Соответствующие зависимости

Код: Выделить всё

org.springframework.boot
spring-boot-starter-parent
4.0.2



org.springframework.boot
spring-boot-starter-security



org.springframework.security
spring-security-test
test



org.springframework.boot
spring-boot-starter-data-jpa-test
test


org.springframework.boot
spring-boot-starter-webmvc-test
test

Ответ Mockito

Код: Выделить всё

MockHttpServletRequest:
HTTP Method = POST
Request URI = /api/v1/products
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Content-Length:"2"]
Body = {}
Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest [http://localhost/api/v1/products?continue]}

Handler:
Type = null

Async:
Async started = false
Async result = null

Resolved Exception:
Type = null

ModelAndView:
View name = null
View = null
Model = null

FlashMap:
Attributes = null

MockHttpServletResponse:
Status = 401
Error message = Unauthorized
Headers = [WWW-Authenticate:"Basic realm="Realm"", X-Content-Type-Options:"nosniff", X-XSS-Protection:"0", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []

java.lang.AssertionError: Status expected: but was:
Expected :201
Actual   :401
Большое спасибо.


Подробнее здесь: https://stackoverflow.com/questions/798 ... ized-in-mo
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»