54. 토큰 만들기

송민경's avatar
Apr 02, 2024
54. 토큰 만들기

1. JwtUtil 클래스 만들기

  • 내가 생성하고 검증할 것이기에 RSA할 필요 없음
  • SIGN은 나중에 환경변수(OS변수)로 사용해야 함
package shop.mtcoding.blog._core.utils; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import shop.mtcoding.blog.user.User; import java.util.Date; public class JwtUtil { // 토큰 생성 public static String create(User user){ // user 객체가 필요함 String jwt = JWT.create() .withSubject("blog") .withExpiresAt(new Date(System.currentTimeMillis() + 1000L * 60L * 60L)) .withClaim("id", user.getId()) .withClaim("username", user.getUsername()) .sign(Algorithm.HMAC512("metacoding")); // 나중에 환경변수(OS변수)로 사용해야 함 return jwt; } // 토큰 검증 public static void verify(){ } }
  • test 해보기
env: // 바껴도 됨 java_home: ${JAVA_HOME}
notion image
package shop.mtcoding.blog._core.utils; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import shop.mtcoding.blog.user.User; @DataJpaTest public class JwtUtilTest { @Test public void create_test() { //given User user = User. builder () .id(1) .username("ssar") .build(); //when String jwt = JwtUtil . create (user); System.out.println("jwt: " + jwt); } }
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJibG9nIiwiaWQiOjEsImV4cCI6MTcxMjAzODcwMSwidXNlcm5hbWUiOiJzc2FyIn0.VGGXfy8W0x0wuQ8Yz1IT7tqG9efxTm-v_Uw-h4QiiG1OshXZ-PLtRSVWREO9n6JUtVpONyuG4Hmkfmj_mMzLEQ
notion image
notion image
Share article

vosw1