Skip to content

feat: 인증/인가를 위한 JWT 토큰 발급 로직 구현#4

Merged
chock-cho merged 14 commits intodevfrom
feature/JWT
Dec 27, 2024
Merged

feat: 인증/인가를 위한 JWT 토큰 발급 로직 구현#4
chock-cho merged 14 commits intodevfrom
feature/JWT

Conversation

@Ji-soo708
Copy link
Member

@Ji-soo708 Ji-soo708 commented Dec 27, 2024

👋 개요

  • 앞으로의 인증/인가를 위한 JWT 토큰 발급 로직을 구현했습니다

💻 작업사항

  • JWT 토큰 발급 로직 구현
  • 임의의 Member 모델 작성
  • JWT 토큰 발급 로직 검증을 위한 테스트 코드 추가
  • kotest 테스트용 환경 설정

⚠️ 주의사항

  • JWT 관련 테스트 코드 추가하느라 같이 이 PR에서 환경 설정도 해주었는데 그래서 많은 파일이 수정되었네요... 커밋별로 봐주시면 더 좋을 거 같아요!
  • 이번에 코틀린으로 하니까 코틀린스러운 테스트코드 스타일이 있나 해서 찾아봤는데 kotest가 유명하더라고요. 수정님도 괜찮다면 kotest로 테코 작성하면 어떨지 궁금해요. ㅎㅎ
  • 개선/수정할 부분 코멘트 남겨주시면 감사합니다

@Ji-soo708 Ji-soo708 added ⚙️ CHORE config, workflow.yaml ✨ FEATURE 기능 추가 labels Dec 27, 2024
@Ji-soo708 Ji-soo708 self-assigned this Dec 27, 2024
Comment on lines +13 to +14
@SpringBootTest
class JwtTokenProviderTest : BehaviorSpec() {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저는 kotest를 이용해서 테스트코드를 작성해봤습니다!

실제로 많이 쓰이는 라이브러리이고 Kotlin을 활용한 자연스러운 DSL을 제공해서 좋은 거 같아요. 혹시 제가 임의로 넣긴 했지만 수정님은 어떠신가요??

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 kotest를 사용해 본 경험이 있는데, 정말 유용한 라이브러리라고 생각합니다! 말씀해주신 코틀린의 DSL을 활용해서 가독성 높은 테스트 코드를 작성할 수 있다는 점에서 장점을 지닌다고 느꼈어요.

특히 kotest의 shouldexpect 같은 직관적인 구문, 다양한 Matcher와 함께 제공되는 Assertion 기능 덕분에 테스트 의도를 간결하고 명확히 표현할 수 있어서 좋더라고요.

저도 테스트코드 작성에서 kotest를 활용하는 데 찬성합니다 😄

@Ji-soo708 Ji-soo708 requested a review from chock-cho December 27, 2024 04:26
Copy link
Member

@chock-cho chock-cho left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

전반적으로 인증/인가 로직에 대한 기본적인 방향을 잘 작성해주신 것 같습니다! ☺️
몇 가지 자잘한 피드백 코멘트 드렸으니, 의견 함께 나누어보고 머지하면 좋을 것 같습니다

Comment on lines +13 to +14
@SpringBootTest
class JwtTokenProviderTest : BehaviorSpec() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 kotest를 사용해 본 경험이 있는데, 정말 유용한 라이브러리라고 생각합니다! 말씀해주신 코틀린의 DSL을 활용해서 가독성 높은 테스트 코드를 작성할 수 있다는 점에서 장점을 지닌다고 느꼈어요.

특히 kotest의 shouldexpect 같은 직관적인 구문, 다양한 Matcher와 함께 제공되는 Assertion 기능 덕분에 테스트 의도를 간결하고 명확히 표현할 수 있어서 좋더라고요.

저도 테스트코드 작성에서 kotest를 활용하는 데 찬성합니다 😄

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

현재 generateAccessTokengenerateRefreshToken이 유사한 구조를 지니고 있어서, 공통 로직을 추출하는 방향으로 가면 코드의 가독성이 조금 더 개선될 수 있지 않을까 싶습니다!

fun generateAccessToken(authentication: Authentication): String {
  return generateToken(
      tokenType = ACCESS_TOKEN_TYPE_VALUE,
      authentication = authentication, 
      expirationDate = generateAccessTokenExpiration()
  )
}

fun generateRefreshToken(authentication: Authentication): String {
  return generateToken(
      tokenType = REFRESH_TOKEN_TYPE_VALUE,
      authentication = authentication, 
      expirationDate = generateAccessTokenExpiration()
  )
}

private fun generateToken(
    tokenType: String,
    authentication: Authentication,
    expirationDate: Date
): String {
    val authorities = authentication.authorities.joinToString(",") { it.authority }

    return Jwts.builder()
        .setHeader(mapOf(TOKEN_TYPE_HEADER_KEY to tokenType))
        .setClaims(
            mapOf(
                USER_ID_CLAIM_KEY to authentication.name,
                AUTHORITIES_CLAIM_KEY to authorities
            )
        ) 
        .setExpiration(expirationDate) 
        .encryptWith(signKey, Jwts.ENC.A128CBC_HS256)
        .compact() 
}

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

확실히 공통 로직을 별도로 빼니까 가독성이 더 좋네요! 반영했습니다. 👍

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

현재 단계에서 큰 틀에서 Test Code 너무 잘 작성해주신 것 같습니다! ☺️

핵심적인 기능(토큰 생성, 파싱, 예외처리)에 대한 검증이 잘 이루어졌고, 초기 단계에서 안정성을 충분하게 확보할 수 있을 것 같습니다.

MVP 목표 달성한 이후에, 발생할 수 있는 시나리오 생각하면서 Refresh Token 관련 로직, Expiration 처리, Signature 검증 같은 추가적인 Test Code 작성도 함께 고려해보면 좋을 것 같아요! 👍

@Ji-soo708 Ji-soo708 requested a review from chock-cho December 27, 2024 07:16
Copy link
Member

@chock-cho chock-cho left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! 수고하셨습니다🍀

@chock-cho chock-cho merged commit 327f5af into dev Dec 27, 2024
@chock-cho chock-cho deleted the feature/JWT branch December 27, 2024 07:19
Ji-soo708 added a commit that referenced this pull request Jan 26, 2025
* chore: add h2 dependency

* chore: add yaml for test

* chore: add security and jjwt dependency

* feat: add Exception for Authentication

* feat: add JwtTokenProvider

* chore: add kotest dependency

* chore: add access/refresh expriration variable

* feat: add TokenGateway

* feat: add Member model

* refactor: add ApplicationConfig for application-wide settings

* test: set up test environment configuration

* test: add JwtTokenProvider's test code

* refactor: change token property variable names in yaml

* refact: refactor JWT token generation by extracting common logic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

⚙️ CHORE config, workflow.yaml ✨ FEATURE 기능 추가

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants