Skip to content

Commit

Permalink
[�Refactor #151] JWT Subject 개인정보 제거 (#154)
Browse files Browse the repository at this point in the history
* [refactor] JWT 생성 로직 변경

- JWT 생성시 subject에 개인정보(이메일)이 아닌 PK값이 들어가도록 변경
- 검증 토큰을 이용한 인증 객체 생성 시 subject 이메일 -> PK 변경에 따라 PK로 회원 찾도록 변경

* [refactor] : 토큰 generate 메서드 파라미터 변경으로 인한 리팩토링

* [refactor] : 토큰 generate 메서드 파라미터 변경으로 인한 리팩토링

* [refactor] : 토큰 generate 메서드 파라미터 변경으로 인한 리팩토링
  • Loading branch information
dudxo authored Nov 21, 2024
1 parent 503175d commit e08aedf
Show file tree
Hide file tree
Showing 7 changed files with 37 additions and 31 deletions.
14 changes: 7 additions & 7 deletions src/main/java/com/dnd/gongmuin/auth/service/AuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,13 @@ public TempSignResponse tempSignUp(TempSignUpRequest tempSignUpRequest, HttpServ
throw new NotFoundException(MemberErrorCode.NOT_FOUND_MEMBER);
}

memberRepository.save(member);
Member savedMember = memberRepository.save(member);

AuthInfo authInfo = AuthInfo.of(member.getSocialName(), member.getSocialEmail(), member.getRole());
CustomOauth2User customOauth2User = new CustomOauth2User(authInfo);

tokenProvider.generateRefreshToken(customOauth2User, now);
String accessToken = tokenProvider.generateAccessToken(customOauth2User, now);
tokenProvider.generateRefreshToken(savedMember, customOauth2User, now);
String accessToken = tokenProvider.generateAccessToken(savedMember, customOauth2User, now);
response.addCookie(cookieUtil.createCookie(accessToken));

return new TempSignResponse(true);
Expand All @@ -98,8 +98,8 @@ public TempSignResponse tempSignIn(TempSignInRequest tempSignInRequest, HttpServ
AuthInfo authInfo = AuthInfo.of(member.getSocialName(), member.getSocialEmail(), member.getRole());
CustomOauth2User customOauth2User = new CustomOauth2User(authInfo);

tokenProvider.generateRefreshToken(customOauth2User, now);
String accessToken = tokenProvider.generateAccessToken(customOauth2User, now);
tokenProvider.generateRefreshToken(member, customOauth2User, now);
String accessToken = tokenProvider.generateAccessToken(member, customOauth2User, now);
response.addCookie(cookieUtil.createCookie(accessToken));

return new TempSignResponse(true);
Expand Down Expand Up @@ -175,8 +175,8 @@ public ReissueResponse reissue(HttpServletRequest request, HttpServletResponse r

CustomOauth2User customUser = new CustomOauth2User(
AuthInfo.of(member.getSocialName(), member.getSocialEmail(), member.getRole()));
String reissuedAccessToken = tokenProvider.generateAccessToken(customUser, new Date());
tokenProvider.generateRefreshToken(customUser, new Date());
String reissuedAccessToken = tokenProvider.generateAccessToken(member, customUser, new Date());
tokenProvider.generateRefreshToken(member, customUser, new Date());

response.addCookie(cookieUtil.createCookie(reissuedAccessToken));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
Member findmember = memberRepository.findBySocialEmail(socialEmail)
.orElseThrow(() -> new NotFoundException(MemberErrorCode.NOT_FOUND_MEMBER));

String token = tokenProvider.generateAccessToken(customOauth2User, new Date());
tokenProvider.generateRefreshToken(customOauth2User, new Date());
String token = tokenProvider.generateAccessToken(findmember, customOauth2User, new Date());
tokenProvider.generateRefreshToken(findmember, customOauth2User, new Date());

response.addCookie(cookieUtil.createCookie(token));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,25 +54,25 @@ private void initSecretKey() {
this.secretKey = Keys.hmacShaKeyFor(key.getBytes());
}

public String generateAccessToken(CustomOauth2User authentication, Date now) {
return generateToken(authentication, ACCESS_TOKEN_EXPIRE_TIME, now);
public String generateAccessToken(Member findMember, CustomOauth2User authentication, Date now) {
return generateToken(findMember, authentication, ACCESS_TOKEN_EXPIRE_TIME, now);
}

public String generateRefreshToken(CustomOauth2User authentication, Date now) {
String refreshToken = generateToken(authentication, REFRESH_TOKEN_EXPIRE_TIME, now);
public String generateRefreshToken(Member findMember, CustomOauth2User authentication, Date now) {
String refreshToken = generateToken(findMember, authentication, REFRESH_TOKEN_EXPIRE_TIME, now);

// redis Refresh 저장
redisUtil.setValues("RT:" + authentication.getEmail(), refreshToken,
Duration.ofMillis(REFRESH_TOKEN_EXPIRE_TIME));
return refreshToken;
}

private String generateToken(CustomOauth2User authentication, long tokenExpireTime, Date now) {
private String generateToken(Member findMember, CustomOauth2User authentication, long tokenExpireTime, Date now) {
Date expiredTime = createExpiredDateWithTokenType(now, tokenExpireTime);
String authorities = getAuthorities(authentication);

return Jwts.builder()
.subject(authentication.getEmail())
.subject(String.valueOf(findMember.getId()))
.claim(ROLE_KEY, authorities)
.issuedAt(now)
.expiration(expiredTime)
Expand All @@ -94,8 +94,8 @@ public Authentication getAuthentication(String token) {
Claims claims = parseToken(token);
List<SimpleGrantedAuthority> authorities = getAuthorities(claims);

String socialEmail = claims.getSubject();
Member principal = memberRepository.findBySocialEmail(socialEmail)
String subject = claims.getSubject();
Member principal = memberRepository.findById(Long.valueOf(subject))
.orElseThrow(() -> new NotFoundException(MemberErrorCode.NOT_FOUND_MEMBER));

return new UsernamePasswordAuthenticationToken(principal, token, authorities);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ void signUp() throws Exception {
savedMember.getSocialEmail(),
savedMember.getRole()
);
String token = tokenProvider.generateAccessToken(new CustomOauth2User(authInfo), new Date());
String token = tokenProvider.generateAccessToken(savedMember, new CustomOauth2User(authInfo), new Date());
this.loginMember = savedMember;
this.accessToken = new Cookie("Authorization", token);

Expand Down
14 changes: 10 additions & 4 deletions src/test/java/com/dnd/gongmuin/auth/service/AuthServiceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -174,10 +174,16 @@ void reissue() {
given(cookieUtil.createCookie(anyString())).willReturn(new Cookie("Authorization", "reissueToken"));
given(tokenProvider.getAuthentication(anyString())).willReturn(authentication);
given(redisUtil.getValues(anyString())).willReturn("refreshToken");
given(tokenProvider.generateAccessToken(any(CustomOauth2User.class), any(Date.class))).willReturn(
"reissueToken");
given(tokenProvider.generateRefreshToken(any(CustomOauth2User.class), any(Date.class))).willReturn(
"reissueToken");
given(tokenProvider.generateAccessToken(
any(Member.class),
any(CustomOauth2User.class),
any(Date.class)))
.willReturn("reissueToken");
given(tokenProvider.generateRefreshToken(
any(Member.class),
any(CustomOauth2User.class),
any(Date.class)))
.willReturn("reissueToken");

// when
ReissueResponse response = authService.reissue(mockRequest, mockResponse);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ public void setUpMember() {
savedMember.getSocialEmail(),
savedMember.getRole()
);
String token = tokenProvider.generateAccessToken(new CustomOauth2User(authInfo), new Date());
tokenProvider.generateRefreshToken(new CustomOauth2User(authInfo), new Date());
String token = tokenProvider.generateAccessToken(savedMember, new CustomOauth2User(authInfo), new Date());
tokenProvider.generateRefreshToken(savedMember, new CustomOauth2User(authInfo), new Date());
this.loginMember = savedMember;
this.accessToken = cookieUtil.createCookie(token);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ void generateAccessToken() {
CustomOauth2User authentication = new CustomOauth2User(authInfo);

// when
String accessToken = tokenProvider.generateAccessToken(authentication, now);
String accessToken = tokenProvider.generateAccessToken(MemberFixture.member(1L), authentication, now);
Claims claims = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(accessToken).getPayload();
Date expiration = claims.getExpiration();

Expand All @@ -85,25 +85,25 @@ void generateRefreshToken() {
CustomOauth2User authentication = new CustomOauth2User(authInfo);

// when
String accessToken = tokenProvider.generateRefreshToken(authentication, now);
String accessToken = tokenProvider.generateRefreshToken(MemberFixture.member(1L), authentication, now);
Claims claims = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(accessToken).getPayload();
Date expiration = claims.getExpiration();

// then
assertThat(expiration.getTime()).isCloseTo(expectedExpirationTime, within(1000L));
}

@DisplayName("토큰 파싱을 통해 만들어진 인증 객체의 이메일은 토큰 정보의 이메일 값과 동일하다.")
@DisplayName("토큰 파싱을 통해 만들어진 인증 객체의 이메일은 회원 이메일과 동일하다.")
@Test
void getAuthentication() {
// given
Date now = new Date();

Member member = MemberFixture.member();
Member member = MemberFixture.member(1L);
CustomOauth2User customOauth2User = new CustomOauth2User(authInfo);
String accessToken = tokenProvider.generateAccessToken(customOauth2User, now);
String accessToken = tokenProvider.generateAccessToken(member, customOauth2User, now);

given(memberRepository.findBySocialEmail(anyString())).willReturn(Optional.ofNullable(member));
given(memberRepository.findById(anyLong())).willReturn(Optional.ofNullable(member));

// when
Authentication authentication = tokenProvider.getAuthentication(accessToken);
Expand All @@ -121,7 +121,7 @@ void validateToken() {
Date past = new Date(124, 6, 30, 16, 0, 0);

CustomOauth2User customOauth2User = new CustomOauth2User(authInfo);
String accessToken = tokenProvider.generateRefreshToken(customOauth2User, past);
String accessToken = tokenProvider.generateRefreshToken(MemberFixture.member(1L), customOauth2User, past);

// when
boolean result = tokenProvider.validateToken(accessToken, new Date());
Expand Down

0 comments on commit e08aedf

Please sign in to comment.