JWT 생성시 필요한 정보들을 클래스와 yml 설정을 통해 관리해보자.
💡 JWT 구현을 위해 비밀키, 발급자, 만료 시간 등 정보들이 필요하다.그 정보들을.yml
로 관리하고class
로 사용해보자
xxx.yml 을 사용하는 이유는 보안 때문.
비밀키가 유출되면 안 된다.
🎯 JWTProperties 를 만들자.
JWT를 생성할 때 발급자, 비밀키, 만료 시간만 필요하다고 가정하자.
@ConfigurationProperties(prefix = "app.jwt") @Getter @Setter public class JWTProperties { private String issuer; private String secretKey; private Long expired; public Key getSecretKey() { byte[] keyBytes = DatatypeConverter.parseBase64Binary(secretKey); return new SecretKeySpec(keyBytes, SignatureAlgorithm.HS256.getJcaName()); } }
issuer
: 발급자secretKey
: 비밀키expired
: 만료 시간getSecretKey()
: 오버라이딩한 이유는 비밀키를 숨기기 위함이다.@Setter
: .yml
에 설정된 값을 바인딩하기 위해 필요하다.위의 클래스는
record
로도 변환이 가능한데,record
는 자동으로 getter
가 제공되면서 비밀키의 유출이 가능한 것 같아 사용하지 않았다.🎯 application-jwt.yml
위의 정보들은 프라이빗하게 관리할 것.
특히 비밀키가 유출된다면 인증&인가 처리가 무효화되므로
.yml
로 따로 관리한다.resources -> app -> jwt -> application-jwt.yml
의 내용이다.app: jwt: issuer: lkdcode // 발급자 정보 secret_key: secretlkdcode // 터미널에서 `openssl rand -hex 64` 로 생성 expired: 1_800_000 // 만료시간
🎯 위의 설정 정보를 application.yml 에 등록해야한다.
application.yml
에서 바로 써도 되지만, 관리를 위해 분리했다.application.yml
에 경로를 추가하자.... spring: config: import: - classpath:/app/jwt/application-jwt.yml ...
🎯 Application(Main) 에 바인딩을 위한 애노테이션을 추가하자
프로젝트가 시작되는
Application(Main)
에 바인딩을 위한@EnableConfigurationProperties(JWTProperties.class)
애노테이션을 명시해줍니다.@SpringBootApplication @EnableJpaAuditing @EnableConfigurationProperties(JWTProperties.class) // 외부 설정 파일의 값을 읽어와서 자바 빈으로 매핑할 때 사용 public class LkdcodeApplication { public static void main(String[] args) { SpringApplication.run(LkdcodeApplication.class, args); } }
🎯 설정 값을 잘 읽어오는지 확인해보자.
간단한 테스트 코드로 확인한다.
@SpringBootTest class JWTPropertiesTest { @Autowired private JWTProperties jwtProperties; @Test void jwt_설정값_불러오기_성공_테스트() { // given // when System.out.println("jwtProperties.getIssuer() = " + jwtProperties.getIssuer()); System.out.println("jwtProperties.getExpired() = " + jwtProperties.getExpired()); System.out.println("jwtProperties.getSecretKey() = " + jwtProperties.getSecretKey()); // then assertThat(jwtProperties.getSecretKey()) .isNotNull(); assertThat(jwtProperties.getExpired()) .isNotNull(); assertThat(jwtProperties.getIssuer()) .isNotNull(); } }
암호화처리된 비밀키까지 잘 출력된다.