我在根据角色实施如下所示的 Acuator 测试时遇到问题
这里是Security Config中定义的bean
@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors()
.and()
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(handler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeHttpRequests()
.requestMatchers(HttpMethod.GET,"/actuator/**").hasRole("ADMIN")
.anyRequest().authenticated();
httpSecurity.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
return httpSecurity.build();
}
下面是执行器的测试控制器
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class ActutorIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
@WithMockUser(roles = "ADMIN")
public void testActuatorEndpointsAccessWithSuperAdminRole() throws Exception {
mockMvc.perform(get("/actuator/health"))
.andDo(print())
.andExpect(status().isOk());
}
@Test
@WithMockUser(roles = "USER")
public void testActuatorEndpointsAccessWithUserRole() throws Exception {
mockMvc.perform(get("/actuator/health"))
.andDo(print())
.andExpect(status().isForbidden());
}
}
即使只有管理员可以访问 /actuator,我得到 testActuatorEndpointsAccessWithUserRole 的 200 个结果而不是 403。
这是我运行 testActuatorEndpointsAccessWithUserRole 方法时显示的错误消息
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", 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:<403> but was:<200>
Expected :403
Actual :200
我该如何解决?