✏️ Ut
- Map 을 JSON 으로 변환시켜주는 객체
- Claims (Client 정보) 를 Map 에 저장하기 때문에 변환 과정이 필요하다.
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
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;
}
}
}
}
✏️ Access Token 생성
📍 생성 로직 구현
Map<String, Object> claims
int seconds
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 String genToken(Map<String, Object> claims, int seconds) {
long now = new Date().getTime();
Date accessTokenExpiresIn = new Date(now + 1000L * seconds);
return Jwts.builder()
.claim("body", Ut.json.toStr(claims))
.setExpiration(accessTokenExpiresIn)
.signWith(getSecretKey(), SignatureAlgorithm.HS512)
.compact();
}
}
📍 test case
- claims 정보와 만료시간을 생성해 getToken 을 호출해 JWT 를 생성한다.
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
class JwtProviderTest {
@Autowired private JwtProvider jwtProvider;
@Value("${custom.jwt.secretKey}")
private String secretKeyPlain;
@Test
@DisplayName("accessToken 을 얻는다.")
void t5() {
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(accessToken).isNotNull();
}
}
accessToken : eyJhbGciOiJIUzUxMiJ9.eyJib2R5Ijoie1wiaWRcIjoxLFwidXNlcm5hbWVcIjpcImFkbWluXCJ9IiwiZXhwIjoxNjg0MzA4NDY1fQ.wo27VuF8CEimIYyNsEqnKHjZTdj7udKLlhRNOsPZ40Ks_jCpGq3aaPkFPv0QQAV5Wo1LikeaPX5qK4f0MmkSnw