Spring Security+;弹簧启动测试控制器
我正在测试家庭控制器Spring Security+;弹簧启动测试控制器,spring,spring-boot,junit,spring-test,spring-security-test,Spring,Spring Boot,Junit,Spring Test,Spring Security Test,我正在测试家庭控制器 @RequestMapping("/") @ResponseBody String home() { return "Hello World!"; } 默认情况下,我使用SpringSecurity作为用户名“user”并作为密码进行测试,但@PreAuthorize不起作用 @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RAN
@RequestMapping("/")
@ResponseBody
String home() {
return "Hello World!";
}
默认情况下,我使用SpringSecurity作为用户名“user”并作为密码进行测试,但@PreAuthorize不起作用
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@PreAuthorize("hasRole('ADMIN')")
public class HomeControllerTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
@WithMockUser(username = "user", password = "test", roles = "ADMIN")
public void home() throws Exception {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).isEqualTo("Hello World!");
}
}
结果
预期结果:
实际结果:
我遗漏了什么吗?尝试将以下内容添加到测试类中:
@TestExecutionListeners(mergeMode = MergeMode.MERGE_WITH_DEFAULTS, listeners = {
WithSecurityContextTestExecutionListener.class
})
如果您没有以下依赖项:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
org.springframework.security
弹簧安全性试验
测试
Spring安全性需要一个默认情况下不在测试中的额外侦听器,因此您需要告诉Spring通过在
merge
模式中指定@TestExecutionListeners
注释来添加它,以便它将当前列出的侦听器与您要添加的侦听器合并(在本例中)使用安全ContextTestExecutionListener
谢谢,但它不起作用,我收到了相同的结果:/WITH MOCKUSER尝试向中的角色
添加角色
。Spring security默认情况下检查前缀角色
(但在@PreAuthorize
中,将其保留为管理员
)您正在调用一个真正的控制器,因此在这里使用@WithMockUser
几乎毫无用处。只有在直接调用控制器上的home()
方法时,这才有效。假设您具有登录的基本身份验证设置,则应随请求一起发送凭据。另外,对您的测试用例进行@PreAuthorize
也不会取得任何效果。