-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[#8] 카카오 로그인 OIDC -> 자체 JWT 발급 방식 변경 #11
Open
hynxp
wants to merge
20
commits into
main
Choose a base branch
from
feat/oidc-to-jwt
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
0c49b91
refactor: 카카오 auth 링크 api 제거
hynxp 31c8a08
chore: jwt 관련 라이브러리 추가
hynxp 3b844b8
chore: jwt secret key property 추가
hynxp b5b4ace
feat: 우동 자체 토큰 발급기 JwtTokenProvider 추가
hynxp fe01aa7
test: JwtTokenProvider 테스트
hynxp 4bb6b3f
feat: idToken -> 자체 JWT 발급 방식으로 변경
hynxp 6d3ad7d
test: 사용자 정보 저장, 재발급된 refresh_token 저장 테스트
hynxp 03cd3f7
test: 미사용 코드 제거 및 테스트 코드 수정
hynxp b40fad9
feat: 카카오 api refresh_token 갱신 api 제거
hynxp 6c59464
feat: 토큰 검증 시 만료될 토큰이면 예외 던지기
hynxp 923feb6
test: 중복 테스트 제거, 만료된 토큰 예외 테스트
hynxp f946bec
refactor: 미사용 코드 제거
hynxp 553e7f0
refactor: 액세스 토큰, 리프레쉬 토큰의 만료일시를 계산해서 반환
hynxp c4cdec1
test: 토큰을 만들었을 때 각 토큰의 만료일시가 제대로 계산됐는지 검증
hynxp 74f68b7
refactor: 토큰 만료시간 설정파일로 분리
hynxp f9033ae
refactor: 토큰 만료시간 주석 제거...
hynxp fa7b4ea
refactor: 토큰 payload 내 subject 추출 메서드명 변경
hynxp db713ab
refactor: 잘못된 토큰 검증 시 예외 로깅 추가
hynxp a895aec
refactor: 멤버 저장, 소셜 정보로 조회 로직 분리
hynxp 23b806f
refactor: 재발급 리프레쉬 토큰 저장 로직 이동 MemberService->AuthService
hynxp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
57 changes: 40 additions & 17 deletions
57
src/main/java/com/hyun/udong/auth/application/service/AuthService.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,40 +1,63 @@ | ||
package com.hyun.udong.auth.application.service; | ||
|
||
import com.hyun.udong.auth.infrastructure.client.KakaoOAuthClient; | ||
import com.hyun.udong.auth.presentation.dto.AccessTokenResponse; | ||
import com.hyun.udong.auth.presentation.dto.AuthTokens; | ||
import com.hyun.udong.auth.presentation.dto.KakaoProfileResponse; | ||
import com.hyun.udong.auth.presentation.dto.KakaoTokenResponse; | ||
import com.hyun.udong.auth.presentation.dto.LoginResponse; | ||
import com.hyun.udong.auth.util.JwtTokenProvider; | ||
import com.hyun.udong.member.application.service.MemberService; | ||
import com.hyun.udong.member.domain.Member; | ||
import com.hyun.udong.member.domain.SocialType; | ||
import com.hyun.udong.member.exception.MemberNotFoundException; | ||
import com.hyun.udong.member.infrastructure.repository.MemberRepository; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.stereotype.Service; | ||
import org.springframework.transaction.annotation.Transactional; | ||
|
||
@Service | ||
@Transactional(readOnly = true) | ||
@RequiredArgsConstructor | ||
public class AuthService { | ||
|
||
private final KakaoOAuthClient kakaoOAuthClient; | ||
private final MemberService memberService; | ||
private final MemberRepository memberRepository; | ||
private final JwtTokenProvider jwtTokenProvider; | ||
|
||
public String getOAuthUrl() { | ||
return kakaoOAuthClient.getOAuthUrl(); | ||
} | ||
|
||
public AccessTokenResponse kakaoLogin(String code) { | ||
@Transactional | ||
public LoginResponse kakaoLogin(String code) { | ||
KakaoTokenResponse kakaoTokenResponse = kakaoOAuthClient.getToken(code); | ||
KakaoProfileResponse profile = kakaoOAuthClient.getUserProfile(kakaoTokenResponse.getAccessToken()); | ||
Member member = profile.toMember(); | ||
member.updateRefreshToken(kakaoTokenResponse.getRefreshToken()); | ||
memberService.save(member); | ||
return new AccessTokenResponse(kakaoTokenResponse.getIdToken(), kakaoTokenResponse.getExpiresIn(), kakaoTokenResponse.getRefreshToken()); | ||
|
||
Member member = memberService.findBySocialIdAndSocialType(profile.getId(), SocialType.KAKAO) | ||
.orElseGet(() -> memberService.save(profile.toMember())); | ||
|
||
String accessToken = jwtTokenProvider.generateAccessToken(member.getId()); | ||
String refreshToken = jwtTokenProvider.generateRefreshToken(member.getId()); | ||
updateRefreshToken(member.getId(), refreshToken); | ||
|
||
AuthTokens authTokens = new AuthTokens(accessToken, jwtTokenProvider.getTokenExpireTime(accessToken), refreshToken, jwtTokenProvider.getTokenExpireTime(refreshToken)); | ||
return new LoginResponse(member.getId(), member.getNickname(), authTokens); | ||
} | ||
|
||
@Transactional | ||
public LoginResponse refreshTokens(String refreshToken) { | ||
Long memberId = Long.parseLong(jwtTokenProvider.getSubjectFromToken(refreshToken)); | ||
String newAccessToken = jwtTokenProvider.generateAccessToken(memberId); | ||
String newRefreshToken = jwtTokenProvider.generateRefreshToken(memberId); | ||
|
||
Member member = updateRefreshToken(memberId, newRefreshToken); | ||
|
||
AuthTokens authTokens = new AuthTokens(newAccessToken, jwtTokenProvider.getTokenExpireTime(newAccessToken), newRefreshToken, jwtTokenProvider.getTokenExpireTime(newRefreshToken)); | ||
return new LoginResponse(member.getId(), member.getNickname(), authTokens); | ||
|
||
} | ||
|
||
public AccessTokenResponse refreshTokens(String refreshToken) { | ||
KakaoTokenResponse kakaoTokenResponse = kakaoOAuthClient.refreshTokens(refreshToken); | ||
if (kakaoTokenResponse.getRefreshToken() != null) { | ||
Member member = memberService.findByRefreshToken(refreshToken); | ||
member.updateRefreshToken(kakaoTokenResponse.getRefreshToken()); | ||
} | ||
return new AccessTokenResponse(kakaoTokenResponse.getIdToken(), kakaoTokenResponse.getExpiresIn(), refreshToken); | ||
private Member updateRefreshToken(Long memberId, String refreshToken) { | ||
Member member = memberRepository.findById(memberId) | ||
.orElseThrow(() -> MemberNotFoundException.EXCEPTION); | ||
member.updateRefreshToken(refreshToken); | ||
return memberRepository.save(member); | ||
} | ||
} |
12 changes: 12 additions & 0 deletions
12
src/main/java/com/hyun/udong/auth/exception/ExpiredTokenException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
package com.hyun.udong.auth.exception; | ||
|
||
import com.hyun.udong.common.exception.ErrorCode; | ||
import com.hyun.udong.common.exception.UdongException; | ||
|
||
public class ExpiredTokenException extends UdongException { | ||
public static final ExpiredTokenException EXCEPTION = new ExpiredTokenException(); | ||
|
||
private ExpiredTokenException() { | ||
super(ErrorCode.TOKEN_EXPIRED); | ||
} | ||
} |
12 changes: 12 additions & 0 deletions
12
src/main/java/com/hyun/udong/auth/exception/InvalidTokenException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
package com.hyun.udong.auth.exception; | ||
|
||
import com.hyun.udong.common.exception.ErrorCode; | ||
import com.hyun.udong.common.exception.UdongException; | ||
|
||
public class InvalidTokenException extends UdongException { | ||
public static final InvalidTokenException EXCEPTION = new InvalidTokenException(); | ||
|
||
private InvalidTokenException() { | ||
super(ErrorCode.INVALID_TOKEN); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 changes: 0 additions & 4 deletions
4
src/main/java/com/hyun/udong/auth/presentation/dto/AccessTokenResponse.java
This file was deleted.
Oops, something went wrong.
7 changes: 7 additions & 0 deletions
7
src/main/java/com/hyun/udong/auth/presentation/dto/AuthTokens.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
package com.hyun.udong.auth.presentation.dto; | ||
|
||
import java.time.LocalDateTime; | ||
|
||
public record AuthTokens(String accessToken, LocalDateTime accessTokenExpDate, String refreshToken, | ||
LocalDateTime refreshTokenExpDate) { | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
18 changes: 18 additions & 0 deletions
18
src/main/java/com/hyun/udong/auth/presentation/dto/LoginResponse.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
package com.hyun.udong.auth.presentation.dto; | ||
|
||
import lombok.Getter; | ||
import lombok.NoArgsConstructor; | ||
|
||
@Getter | ||
@NoArgsConstructor | ||
public class LoginResponse { | ||
private Long id; | ||
private String nickname; | ||
private AuthTokens token; | ||
|
||
public LoginResponse(Long id, String nickname, AuthTokens token) { | ||
this.id = id; | ||
this.nickname = nickname; | ||
this.token = token; | ||
} | ||
} |
77 changes: 77 additions & 0 deletions
77
src/main/java/com/hyun/udong/auth/util/JwtTokenProvider.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
package com.hyun.udong.auth.util; | ||
|
||
import com.hyun.udong.auth.exception.ExpiredTokenException; | ||
import com.hyun.udong.auth.exception.InvalidTokenException; | ||
import io.jsonwebtoken.Claims; | ||
import io.jsonwebtoken.ExpiredJwtException; | ||
import io.jsonwebtoken.Jws; | ||
import io.jsonwebtoken.security.Keys; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.beans.factory.annotation.Value; | ||
import org.springframework.stereotype.Component; | ||
|
||
import java.nio.charset.StandardCharsets; | ||
import java.security.Key; | ||
import java.time.LocalDateTime; | ||
import java.time.ZoneId; | ||
import java.util.Date; | ||
|
||
import static io.jsonwebtoken.Jwts.builder; | ||
import static io.jsonwebtoken.Jwts.parserBuilder; | ||
|
||
@Component | ||
@Slf4j | ||
public class JwtTokenProvider { | ||
|
||
@Value("${ACCESS_TOKEN_EXPIRE_TIME}") | ||
private long accessTokenExpireTime; | ||
|
||
@Value("${REFRESH_TOKEN_EXPIRE_TIME}") | ||
private long refreshTokenExpireTime; | ||
|
||
@Value("${jwt.secret}") | ||
private String secret; | ||
|
||
private Key getSecretKey() { | ||
return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8)); | ||
} | ||
|
||
public String generateAccessToken(Long id) { | ||
return builder() | ||
.setSubject(id.toString()) | ||
.setIssuedAt(new Date()) | ||
.setExpiration(new Date(System.currentTimeMillis() + accessTokenExpireTime)) | ||
.signWith(getSecretKey()) | ||
.compact(); | ||
} | ||
|
||
public String generateRefreshToken(Long id) { | ||
return builder() | ||
.setSubject(id.toString()) | ||
.setIssuedAt(new Date()) | ||
.setExpiration(new Date(System.currentTimeMillis() + refreshTokenExpireTime)) | ||
.signWith(getSecretKey()) | ||
.compact(); | ||
} | ||
|
||
public LocalDateTime getTokenExpireTime(String token) { | ||
Date expiration = parseToken(token).getBody().getExpiration(); | ||
return LocalDateTime.ofInstant(expiration.toInstant(), ZoneId.systemDefault()); | ||
} | ||
|
||
private Jws<Claims> parseToken(String token) { | ||
try { | ||
return parserBuilder().setSigningKey(getSecretKey()).build().parseClaimsJws(token); | ||
} catch (ExpiredJwtException e) { | ||
throw ExpiredTokenException.EXCEPTION; | ||
} catch (Exception e) { | ||
log.error("검증 실패 토큰: {}", token, e); | ||
throw InvalidTokenException.EXCEPTION; | ||
} | ||
} | ||
|
||
public String getSubjectFromToken(String token) { | ||
return parseToken(token).getBody().getSubject(); | ||
} | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
save인데 없으면 기존 회원을 반환하지말고 에러를 던지면 되지 않을까요?
있으면 update 없으면 create 이 과정을 같이 하고 싶으면 upsert 표현을 많이 씁니다.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
AuthService.kakaoLogin()에서 기존회원일 시 member의 id를 받아와야 해서요..! (토큰 발급 시 필요함)
로 바꿔봤는데 괜찮을까요?