我有一个简单的控制器,只能在安全的环境中访问。
在我的应用程序中,我只将其他网址列入白名单,而不是
/user
.
在单机测试中
@GetResponse
我得到的Http状态为401,而不是200。我希望如此,因为它是安全的。
当我实际使用登录用户运行应用程序时,我得到一个200的有效结果。
我如何对请求和任何其他安全控制器路径的行为进行单元测试?
单元测试:
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@InjectMocks
UserController userController;
@Autowired
private MockMvc mockMvc;
@Autowired
private ApplicationContext applicationContext;
@Test
void getUserNone() throws Exception {
mockMvc
.perform(MockMvcRequestBuilders.get("/user"))
.andExpect(status().isOk());
}
}
应用程序:
@SpringBootApplication
public class WebApp extends WebSecurityConfigurerAdapter {
public static void main(final String... args) {
SpringApplication.run(WebApp.class, args);
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests(a -> a
.antMatchers("/error", "/css/**", "/webjars/**").permitAll()
.anyRequest().authenticated()
)
.exceptionHandling(e -> e
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
)
.oauth2Login();
}
}
控制器:
@Controller
public class UserController {
@GetMapping("/user")
public @ResponseBody
Map<String, Object> getUser(@AuthenticationPrincipal final OAuth2User principal) {
if (principal == null) {
return Collections.EMPTY_MAP;
} else {
return Collections.singletonMap("name", principal.getName());
}
}
}
显然,我可以补充
/用户
对于白名单中的路径,但对于应用程序的任何安全部分来说,这都是不正确的。