我尝试禁用控制器单元测试的安全性,但始终出现错误403。
我的单元测试:
@RunWith(SpringRunner.class)
@WebMvcTest(value = MeasureController.class, secure = false)
@AutoConfigureMockMvc(secure = false)
public class MeasureControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private ObjectService objectService;
@Autowired
private MeasureController measureController;
/**
* Test of sayHello method, of class MeasureController.
*
* @throws java.lang.Exception
*/
@Test
public void OnPostShouldReturnCreatedStatusIfEmptyMeasure() throws Exception {
final String url = "/object/" + uuidKey + "/measures/";
this.mvc.perform(post(url)
.content("[]")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated());
verifyZeroInteractions(objectService);
}
}
安全配置:
@Configuration
@EnableResourceServer
public class SecurityResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests()
.antMatchers("/v2/api-docs", "/swagger-resources/**", "/swagger-ui.html", "/webjars/**").permitAll()
.anyRequest().authenticated()
;
}
@Primary
@Bean
public RemoteTokenServices tokenServices() {
final RemoteTokenServices tokenService = new RemoteTokenServices();
tokenService.setCheckTokenEndpointUrl("https://..../oauth/check_token");
tokenService.setClientId(".....");
tokenService.setClientSecret(".....");
return tokenService;
}
}
spring文档说将AutoConfigureMockMvc.secure设置为false或将WebMvcTest.secure设置为false。但是两者都不能禁用安全性。我有事吗?
我使用Spring Boot 2.0.4。和spring-security-oauth2 2.3.3。发布
答案 0 :(得分:0)
“ WebMvcTest.secure”已被弃用。您必须进行控制器测试:
@RunWith(SpringRunner.class)
@WebMvcTest(value = PatientDeviceController.class, excludeAutoConfiguration = SecurityAutoConfiguration.class)
@AutoConfigureMockMvc(secure = false)
答案 1 :(得分:0)
对于其他来这里寻找答案(以及我未来的自我)的人,在Spring Boot 2.2中进行了测试:
Shape shape = new Triangle(50f, 50f);
float areaOfTri = shape.area(); // dispatches to Triangle.area()
shape = new Rectangle(50f, 50f);
float areaOfQuad = shape.area(); // dispatches to Rectangle.area()
@WebMvcTest(controllers = YourController.class,
excludeFilters = { @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = WebSecurityConfigurer.class) },
excludeAutoConfiguration = { SecurityAutoConfiguration.class})
将停止@WebMvcTest拾取实现默认情况下实现的安全性的所有类:
https://docs.spring.io/spring-boot/docs/2.2.1.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests
如果您要添加自己的安全类(很可能是通过扩展excludeFilters
)来阻止Spring拾取并创建这些bean,则需要这样做。WebSecurityConfigurerAdapter
将确保默认的弹簧靴逻辑也不会插入