【发布时间】:2021-09-29 07:59:00
【问题描述】:
在我的 Spring Boot Security 应用程序中,我将我的密钥存储在文件 application.properties 中,它工作得很好。我可以像这样获取我的密钥:
@Value("${secret}")
private String secret;
但是为了测试它并且不要在我的测试中硬编码密码,我需要生成我的令牌并将其放在我的授权标头上(使用 mockMvc),但我可以'不要从测试类访问我的秘密环境变量,即使我将我的环境变量插入到测试路径的 application.properties 文件中。
我如何为我的测试生成令牌:
public class TokenForTest {
public static String generateTokenForTest() {
Date today = new Date();
Date expireDate = new Date(today.getTime() + Long.parseLong("86400000"));
return "Bearer " + Jwts.builder()
.setIssuer("BeatSound API")
.setSubject("1")
.setIssuedAt(today)
.setExpiration(expireDate)
.signWith(SignatureAlgorithm.HS256, "secretKey")
.compact();
}
}
我是如何进行测试的:
@Test
void shouldReturnAllUsers() throws Exception {
String token = TokenForTest.generateTokenForTest();
this.mockMvc.perform(get("/api/v1/user")
.header("Authorization", token))
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(print())
.andExpect(jsonPath("$.[*].id").exists())
.andExpect(jsonPath("$.[*].name").exists())
.andExpect(jsonPath("$.[*].email").exists())
.andExpect(jsonPath("$.[*].password").exists())
}
【问题讨论】:
-
您是如何尝试访问测试中的 env 变量的?使用 MockMvc 时,您还可以查看其 great integration with Spring Security 以避免此类测试的大量安全设置。
标签: java spring-boot testing jwt spring-boot-test