Skip to content

Commit 3584df3

Browse files
committed
refactor: jwt 토큰값 추가 (name)
1 parent a4acc17 commit 3584df3

File tree

4 files changed

+100
-51
lines changed

4 files changed

+100
-51
lines changed

src/main/java/com/example/log4u/common/oauth2/controller/OAuth2Controller.java

Lines changed: 38 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@
33
import org.springframework.http.HttpStatus;
44
import org.springframework.http.ResponseEntity;
55
import org.springframework.web.bind.annotation.GetMapping;
6-
import org.springframework.web.bind.annotation.PostMapping;
76
import org.springframework.web.bind.annotation.RequestMapping;
87
import org.springframework.web.bind.annotation.RestController;
98

109
import com.example.log4u.common.oauth2.jwt.JwtUtil;
10+
import com.example.log4u.common.oauth2.repository.RefreshTokenRepository;
11+
import com.example.log4u.common.oauth2.service.RefreshTokenService;
1112

1213
import io.jsonwebtoken.ExpiredJwtException;
1314
import jakarta.servlet.http.Cookie;
@@ -21,10 +22,12 @@
2122
public class OAuth2Controller {
2223

2324
private final JwtUtil jwtUtil;
24-
25+
private final RefreshTokenService refreshTokenService;
26+
private final RefreshTokenRepository refreshTokenRepository;
27+
2528
@GetMapping("/token/reissue")
2629
public ResponseEntity<?> reissue(
27-
HttpServletRequest request,
30+
HttpServletRequest request,
2831
HttpServletResponse response
2932
) {
3033
// 리프레시 토큰 추출
@@ -35,44 +38,54 @@ public ResponseEntity<?> reissue(
3538
if (cookie.getName().equals("refresh")) {
3639
refresh = cookie.getValue();
3740
}
38-
if( cookie.getName().equals("access") ) {
41+
if (cookie.getName().equals("access")) {
3942
access = cookie.getValue();
4043
}
4144
}
4245

43-
// if (refresh == null) {
44-
// // 리프레시 토큰이 없는 경우
45-
// return new ResponseEntity<>("잘못된 요청입니다..", HttpStatus.BAD_REQUEST);
46-
// }
46+
if (refresh == null) {
47+
// 리프레시 토큰이 없는 경우
48+
return new ResponseEntity<>("잘못된 요청입니다..", HttpStatus.BAD_REQUEST);
49+
}
4750

4851
// 리프레시 토큰 만료 체크
49-
// try {
50-
// jwtUtil.isExpired(refresh);
51-
// } catch (ExpiredJwtException e) {
52-
// return new ResponseEntity<>("리프레시 토큰이 만료되었습니다.", HttpStatus.UNAUTHORIZED);
53-
// }
52+
try {
53+
jwtUtil.isExpired(refresh);
54+
} catch (ExpiredJwtException e) {
55+
return new ResponseEntity<>("리프레시 토큰이 만료되었습니다.", HttpStatus.UNAUTHORIZED);
56+
}
5457

5558
// 토큰이 refresh인지 확인 (발급시 페이로드에 명시)
56-
// String category = jwtUtil.getCategory(refresh);
57-
// if (!category.equals("refresh")) {
58-
// return new ResponseEntity<>("잘못된 토큰입니다.", HttpStatus.BAD_REQUEST);
59-
// }
59+
String category = jwtUtil.getTokenType(refresh);
60+
if (!category.equals("refresh")) {
61+
return new ResponseEntity<>("잘못된 토큰입니다.", HttpStatus.BAD_REQUEST);
62+
}
63+
64+
createNewTokens(response, access, refresh);
65+
return new ResponseEntity<>(HttpStatus.OK);
66+
}
67+
68+
private void createNewTokens(HttpServletResponse response, String access, String refresh) {
69+
// 기존 리프레시 토큰 삭제
70+
refreshTokenRepository.deleteByRefresh(refresh);
6071

6172
Long userId = jwtUtil.getUserId(access);
6273
String role = jwtUtil.getRole(access);
74+
String name = jwtUtil.getName(access);
6375

64-
// 액세스 토큰 새로 생성
65-
String newAccessToken = jwtUtil.createJwt("access", userId, role, 600000L);
66-
String newRefreshToken = jwtUtil.createJwt("refresh", userId, role, 600000L);
67-
68-
// 액세스 토큰 헤더 설정
69-
//response.setHeader("access", newAccessToken);
76+
String newAccessToken = jwtUtil.createJwt("access", userId, name, role, 600000L);
77+
String newRefreshToken = jwtUtil.createJwt("refresh", userId, name, role, 600000L);
7078

71-
// Refresh Token Rotate
7279
response.addCookie(createCookie("refresh", newRefreshToken));
7380
response.addCookie(createCookie("access", newAccessToken));
7481

75-
return new ResponseEntity<>(HttpStatus.OK);
82+
// 새 리프레시 토큰 저장
83+
refreshTokenService.saveRefreshToken(
84+
userId,
85+
name,
86+
refresh
87+
);
88+
7689
}
7790

7891
private Cookie createCookie(String key, String value) {

src/main/java/com/example/log4u/common/oauth2/handler/OAuth2AuthenticationSuccessHandler.java

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import java.io.IOException;
44
import java.util.Collection;
5-
import java.util.Date;
65
import java.util.Iterator;
76
import java.util.Optional;
87

@@ -14,9 +13,8 @@
1413
import org.springframework.stereotype.Component;
1514

1615
import com.example.log4u.common.oauth2.dto.CustomOAuth2User;
17-
import com.example.log4u.common.oauth2.entity.RefreshToken;
1816
import com.example.log4u.common.oauth2.jwt.JwtUtil;
19-
import com.example.log4u.common.oauth2.repository.RefreshTokenRepository;
17+
import com.example.log4u.common.oauth2.service.RefreshTokenService;
2018
import com.example.log4u.domain.user.entity.User;
2119
import com.example.log4u.domain.user.repository.UserRepository;
2220

@@ -30,7 +28,7 @@
3028
public class OAuth2AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
3129

3230
private final UserRepository userRepository;
33-
private final RefreshTokenRepository refreshTokenRepository;
31+
private final RefreshTokenService refreshTokenService;
3432
private final JwtUtil jwtUtil;
3533

3634
private static final String MAIN_PAGE = "http://localhost:3000/";
@@ -80,17 +78,17 @@ private void setCookieAndSaveRefreshToken(
8078
String role = auth.getAuthority();
8179

8280
// 쿠키 생성
83-
String access = jwtUtil.createJwt(ACCESS_TOKEN_KEY, userId, role, accessTokenValidityInSeconds);
84-
String refresh = jwtUtil.createJwt(REFRESH_TOKEN_KEY, userId, role, refreshTokenValidityInSeconds);
81+
String access = jwtUtil.createJwt(ACCESS_TOKEN_KEY, userId, name, role, accessTokenValidityInSeconds);
82+
String refresh = jwtUtil.createJwt(REFRESH_TOKEN_KEY, userId, name, role, refreshTokenValidityInSeconds);
8583
// 저장
86-
saveRefreshToken(refresh, name);
84+
refreshTokenService.saveRefreshToken(null, name, refresh);
8785

8886
response.addCookie(createCookie(ACCESS_TOKEN_KEY, access));
8987
response.addCookie(createCookie(REFRESH_TOKEN_KEY, refresh));
9088
response.setStatus(HttpStatus.OK.value());
9189
}
9290

93-
public void redirectTo(HttpServletResponse response, String redirectUrl) throws IOException {
91+
private void redirectTo(HttpServletResponse response, String redirectUrl) throws IOException {
9492
response.sendRedirect(redirectUrl);
9593
}
9694

@@ -103,15 +101,4 @@ private Cookie createCookie(String key, String value) {
103101
return cookie;
104102
}
105103

106-
public void saveRefreshToken(String refresh, String name) {
107-
Date date = new Date(System.currentTimeMillis() + refreshTokenValidityInSeconds);
108-
109-
RefreshToken refreshToken = new RefreshToken(
110-
null,
111-
name,
112-
refresh,
113-
date.toString()
114-
);
115-
refreshTokenRepository.save(refreshToken);
116-
}
117104
}

src/main/java/com/example/log4u/common/oauth2/jwt/JwtUtil.java

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@ public class JwtUtil {
1818
private final SecretKey secretKey;
1919
private static final String USER_ID_KEY = "userId";
2020
private static final String TOKEN_TYPE_KEY = "token";
21-
21+
private static final String USER_NAME_KEY = "name";
22+
private static final String USER_ROLE_KEY = "role";
23+
2224
public JwtUtil(@Value("${jwt.secret}") String secret) {
2325
secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8),
2426
Jwts.SIG.HS256.key().build().getAlgorithm());
@@ -32,11 +34,24 @@ public Long getUserId(String token) {
3234
.parseSignedClaims(token)
3335
.getPayload()
3436
.get(USER_ID_KEY, Long.class);
35-
} catch(ExpiredJwtException ex){
37+
} catch (ExpiredJwtException ex) {
3638
return ex.getClaims().get(USER_ID_KEY, Long.class);
3739
}
3840
}
3941

42+
public String getName(String token) {
43+
try {
44+
return Jwts.parser()
45+
.verifyWith(secretKey)
46+
.build()
47+
.parseSignedClaims(token)
48+
.getPayload()
49+
.get(USER_NAME_KEY, String.class);
50+
} catch (ExpiredJwtException ex) {
51+
return ex.getClaims().get(USER_NAME_KEY, String.class);
52+
}
53+
}
54+
4055
public String getRole(String token) {
4156
try {
4257
return Jwts.parser()
@@ -45,8 +60,8 @@ public String getRole(String token) {
4560
.parseSignedClaims(token)
4661
.getPayload()
4762
.get("role", String.class);
48-
}catch(ExpiredJwtException ex){
49-
return ex.getClaims().get("role", String.class);
63+
} catch (ExpiredJwtException ex) {
64+
return ex.getClaims().get(USER_ROLE_KEY, String.class);
5065
}
5166
}
5267

@@ -58,7 +73,7 @@ public String getTokenType(String token) {
5873
.parseSignedClaims(token)
5974
.getPayload()
6075
.get(TOKEN_TYPE_KEY, String.class);
61-
}catch(ExpiredJwtException ex){
76+
} catch (ExpiredJwtException ex) {
6277
return ex.getClaims().get(TOKEN_TYPE_KEY, String.class);
6378
}
6479
}
@@ -73,13 +88,14 @@ public Boolean isExpired(String token) {
7388
.before(new Date());
7489
}
7590

76-
public String createJwt(String tokenType, Long userId, String role, Long expiredMs) {
91+
public String createJwt(String tokenType, Long userId, String name, String role, Long expiredMs) {
7792
return Jwts.builder()
7893
.claim(TOKEN_TYPE_KEY, tokenType)
7994
.claim(USER_ID_KEY, userId)
95+
.claim(USER_NAME_KEY, name)
8096
.claim("role", role)
8197
.issuedAt(new Date(System.currentTimeMillis()))
82-
.expiration(new Date(System.currentTimeMillis() + expiredMs*1000))
98+
.expiration(new Date(System.currentTimeMillis() + expiredMs * 1000))
8399
.signWith(secretKey)
84100
.compact();
85101
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.example.log4u.common.oauth2.service;
2+
3+
import java.util.Date;
4+
5+
import org.springframework.beans.factory.annotation.Value;
6+
import org.springframework.stereotype.Service;
7+
8+
import com.example.log4u.common.oauth2.entity.RefreshToken;
9+
import com.example.log4u.common.oauth2.repository.RefreshTokenRepository;
10+
11+
import lombok.RequiredArgsConstructor;
12+
13+
@Service
14+
@RequiredArgsConstructor
15+
public class RefreshTokenService {
16+
17+
private final RefreshTokenRepository refreshTokenRepository;
18+
19+
@Value("${jwt.refresh-token-expire-time-seconds}")
20+
private long refreshTokenValidityInSeconds;
21+
22+
public void saveRefreshToken(Long userId, String refresh, String name) {
23+
Date date = new Date(System.currentTimeMillis() + refreshTokenValidityInSeconds);
24+
25+
RefreshToken refreshToken = new RefreshToken(
26+
userId,
27+
name,
28+
refresh,
29+
date.toString()
30+
);
31+
refreshTokenRepository.save(refreshToken);
32+
}
33+
}

0 commit comments

Comments
 (0)