我正在开发一个 Java 应用程序(使用 Spring Boot),我需要一些帮助:该应用程序接收JWT 令牌作为输入,我在方法中处理该令牌。目前的方法如下:
private UsernamePasswordAuthenticationToken myMethod(HttpServletRequest request) {
// Code that gets the 'token' String
try{
Map<String, String> registry = ((Map<String, String>) (token.getBody().get("registry")));
String sub = ((String) (parsedToken.getBody().get("sub")));
UsernamePasswordAuthenticationToken finalToken = new UsernamePasswordAuthenticationToken(sub, null, null);
return finalToken;
} catch (ExpiredJwtException exception) { // Only here I have the certainty that the token has expired!
// Code that handles the exception
}
Run Code Online (Sandbox Code Playgroud)
}
但是,我需要实现一个逻辑,必须在多个地方检查获取的令牌是否已过期,而不是每次都运行这个方法。我必须知道是否已过期的唯一方法token是 引发的异常ExpiredJwtException。
有没有办法知道令牌是否已过期而不通过捕获的异常?.isExpired例如,如果有一个具有属性或类似属性的“令牌”类,那将非常有用。 …
我正在测试用 Java 和 Spring Boot 编写的应用程序,我有一个问题。我的测试模拟一个 HTTP 请求,该请求仅当customData数据放置在Cookie标头内时才有效。这是我的简单测试的代码:
@Test
public void myFristTest() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post(MY_URL)
.header("Cookie", "customData=customString")
.accept(MediaType.APPLICATION_JSON_VALUE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(ConversionUtil.objectToString(BODY_OF_MY_REQUEST)))
.andExpect(status().isCreated());
}
Run Code Online (Sandbox Code Playgroud)
不幸的是这个测试失败了。用于测试的Java代码如下:
String customData;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("customData")) {
customData = cookie.getValue();
}
}
}
if(customData != null) {
// code that returns HTTP status isCreated
} else {
throw new HttpServerErrorException(HttpStatus.FOUND, "Error 302");
}
Run Code Online (Sandbox Code Playgroud)
在实践中,似乎没有找到customData应该从请求标头中获取的字符串!Cookie …