✏️ Ut
📍 String to Map 변환
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.LinkedHashMap;
import java.util.Map;
public class Ut {
public static class json {
public static Object toStr(Map<String, Object> map) {
try {
return new ObjectMapper().writeValueAsString(map);
} catch (JsonProcessingException e) {
return null;
}
}
public static Map<String, Object> toMap(String jsonStr) {
try {
return new ObjectMapper().readValue(jsonStr, LinkedHashMap.class);
} catch (JsonProcessingException e) {
return null;
}
}
}
}
✏️ JwtProvider
📍 verify() / getClaims()
- 이전 포스딩의 토큰 생성에 이어서 토큰 유효성을 검증하고, 디코딩하는 method 를 구현했다.
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.Date;
import javax.crypto.SecretKey;
import java.util.Base64;
import java.util.Map;
@Component
public class JwtProvider {
...
public boolean verify(String token) {
try {
Jwts.parserBuilder()
.setSigningKey(getSecretKey())
.build()
.parseClaimsJws(token);
} catch (Exception e) {
return false;
}
return true;
}
public Map<String, Object> getClaims(String token) {
String body = Jwts.parserBuilder()
.setSigningKey(getSecretKey())
.build()
.parseClaimsJws(token)
.getBody()
.get("body", String.class);
return Ut.json.toMap(body);
}
}
📍 Test case
@Test
@DisplayName("accessToken 을 통해서 claims 를 얻을 수 있다.")
void t6() {
Map<String, Object> claims = new HashMap<>();
claims.put("id", 1L);
claims.put("username", "admin");
String accessToken = jwtProvider.genToken(claims, 60 * 60 * 5);
System.out.println("accessToken : " + accessToken);
assertThat(jwtProvider.verify(accessToken)).isTrue();
Map<String, Object> claimsFromToken = jwtProvider.getClaims(accessToken);
System.out.println("claimsFromToken : " + claimsFromToken);
}
@Test
@DisplayName("만료된 토큰을 유효하지 않다.")
void t7() {
Map<String, Object> claims = new HashMap<>();
claims.put("id", 1L);
claims.put("username", "admin");
String accessToken = jwtProvider.genToken(claims, -1);
System.out.println("accessToken : " + accessToken);
assertThat(jwtProvider.verify(accessToken)).isFalse();
}