启用安全性的 Spring Boot 1.4 测试?
Posted
技术标签:
【中文标题】启用安全性的 Spring Boot 1.4 测试?【英文标题】:Spring Boot 1.4 testing with Security enabled? 【发布时间】:2016-10-15 12:22:43 【问题描述】:我想知道我应该如何为我的测试验证用户身份?就目前而言,我将编写的所有测试都将失败,因为端点需要授权。
测试代码:
@RunWith(SpringRunner.class)
@WebMvcTest(value = PostController.class)
public class PostControllerTest
@Autowired
private MockMvc mvc;
@MockBean
private PostService postService;
@Test
public void testHome() throws Exception
this.mvc.perform(get("/")).andExpect(status().isOk()).andExpect(view().name("posts"));
我找到的一个解决方案是通过在@WebMvcTest 中将secure 设置为false 来禁用它。但这不是我想要做的。
有什么想法吗?
【问题讨论】:
【参考方案1】:Spring Security 提供了一个@WithMockUser
注解,可以用来表示一个test should be run as a particular user:
@Test
@WithMockUser(username = "test", password = "test", roles = "USER")
public void withMockUser() throws Exception
this.mockMvc.perform(get("/")).andExpect(status().isOk());
或者,如果您使用基本身份验证,您可以发送所需的Authorization
标头:
@Test
public void basicAuth() throws Exception
this.mockMvc
.perform(get("/").header(HttpHeaders.AUTHORIZATION,
"Basic " + Base64Utils.encodeToString("user:secret".getBytes())))
.andExpect(status().isOk());
【讨论】:
Spring Security 甚至内置了对 Testing HTTP Basic Authentication 的支持。 ;) 我看过这个例子,但由于某种原因我无法访问注释。我错过了什么吗? 注解包含在 spring-security-test 中。只需将依赖项 org.springframework.security:spring-security-test 添加到您的项目中【参考方案2】:作为上一个答案的替代方案,可以使用以下内容:
@Test
public void basicAuth() throws Exception
this.mockMvc
.perform(get("/")
.with(SecurityMockMvcRequestPostProcessors.httpBasic("user", "secret"))
)
.andExpect(status().isOk());
因为它会生成相同的标题:
Headers = [Content-Type:"...", Authorization:"Basic dXNlcjpzZWNyZXQ="]
【讨论】:
以上是关于启用安全性的 Spring Boot 1.4 测试?的主要内容,如果未能解决你的问题,请参考以下文章
在 Spring Boot 1.4 中测试 Spring MVC 切片的问题
Spring boot 1.4 测试:配置错误:发现@BootstrapWith 的多个声明
在 Spring Boot 1.4 MVC 测试中使用 @WebMvcTest 设置 MockMvc