From d27afbb75c57da433ff422e487cf80362f0e2743 Mon Sep 17 00:00:00 2001 From: Ahn Jiwan Date: Wed, 24 Jan 2024 18:34:05 +0900 Subject: [PATCH] =?UTF-8?q?:sparkles:=20feat:=20AccessToken=20&=20RefreshT?= =?UTF-8?q?oken=20=EC=9D=B4=EB=B6=84=ED=99=94=20(#144)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/component/JwtTokenProvider.java | 28 +++++++++++++++++-- .../auth/controller/AuthController.java | 4 +-- .../auth/service/CustomUserDetailService.java | 1 + .../diareat/user/service/UserService.java | 3 +- 4 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java index 9bb6aaf..d64c936 100644 --- a/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java +++ b/src/main/java/com/diareat/diareat/auth/component/JwtTokenProvider.java @@ -6,6 +6,7 @@ import io.jsonwebtoken.SignatureAlgorithm; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; @@ -16,6 +17,7 @@ import javax.servlet.http.HttpServletRequest; import java.util.Base64; import java.util.Date; +import java.util.concurrent.TimeUnit; @RequiredArgsConstructor @Component @@ -26,6 +28,8 @@ public class JwtTokenProvider { private final UserDetailsService userDetailsService; + private final RedisTemplate redisTemplate; + // 객체 초기화, secretKey를 Base64로 인코딩 @PostConstruct protected void init() { @@ -33,17 +37,37 @@ protected void init() { } // 토큰 생성 - public String createToken(String userPk) { + public String createAccessToken(String userPk) { Claims claims = Jwts.claims().setSubject(userPk); // JWT payload 에 저장되는 정보단위 Date now = new Date(); return Jwts.builder() .setClaims(claims) // 정보 저장 .setIssuedAt(now) // 토큰 발행 시간 정보 - .setExpiration(new Date(now.getTime() + (720 * 60 * 1000L))) // 토큰 유효시각 설정 (12시간) + .setExpiration(new Date(now.getTime() + (60 * 60 * 1000L))) // 토큰 유효시각 설정 (1시간) .signWith(SignatureAlgorithm.HS256, secretKey) // 암호화 알고리즘과, secret 값 .compact(); } + public String createRefreshToken(String userPk) { + Claims claims = Jwts.claims().setSubject(userPk); // JWT payload 에 저장되는 정보단위 + Date now = new Date(); + String refreshToken = Jwts.builder() + .setClaims(claims) // 정보 저장 + .setIssuedAt(now) // 토큰 발행 시간 정보 + .setExpiration(new Date(now.getTime() + (7 * 24 * 60 * 60 * 1000L))) // 토큰 유효시각 설정 (1주일) + .signWith(SignatureAlgorithm.HS256, secretKey) + .compact(); + + redisTemplate.opsForValue().set( + userPk, + refreshToken, + 7 * 24 * 60 * 60 * 1000L, + TimeUnit.MILLISECONDS + ); + + return refreshToken; + } + // 인증 정보 조회 public Authentication getAuthentication(String token) { UserDetails userDetails = userDetailsService.loadUserByUsername(String.valueOf(this.getUserPk(token))); diff --git a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java index 78a5e8c..e44ef7f 100644 --- a/src/main/java/com/diareat/diareat/auth/controller/AuthController.java +++ b/src/main/java/com/diareat/diareat/auth/controller/AuthController.java @@ -29,7 +29,7 @@ public class AuthController { @PostMapping("/login") public ApiResponse authCheck(@RequestHeader String accessToken) { Long userId = kakaoAuthService.isSignedUp(accessToken); // 유저 고유번호 추출 - String jwt = (userId == null) ? null : jwtTokenProvider.createToken(userId.toString()); // 고유번호가 null이 아니라면 Jwt 토큰 발급 + String jwt = (userId == null) ? null : jwtTokenProvider.createAccessToken(userId.toString()); // 고유번호가 null이 아니라면 Jwt 토큰 발급 return ApiResponse.success(ResponseJwtDto.of(userId, jwt), ResponseCode.USER_LOGIN_SUCCESS.getMessage()); } @@ -38,7 +38,7 @@ public ApiResponse authCheck(@RequestHeader String accessToken) @PostMapping("/join") public ApiResponse saveUser(@Valid @RequestBody JoinUserDto joinUserDto) { Long userId = userService.saveUser(kakaoAuthService.createUserDto(joinUserDto)); - String jwt = jwtTokenProvider.createToken(userId.toString()); + String jwt = jwtTokenProvider.createAccessToken(userId.toString()); return ApiResponse.success(ResponseJwtDto.of(userId, jwt), ResponseCode.USER_CREATE_SUCCESS.getMessage()); } diff --git a/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java b/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java index f74e6fd..fd5b14b 100644 --- a/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java +++ b/src/main/java/com/diareat/diareat/auth/service/CustomUserDetailService.java @@ -16,6 +16,7 @@ public class CustomUserDetailService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException { + return userRepository.findById(Long.parseLong(id)) .orElseThrow(() -> new UsernameNotFoundException(ResponseCode.USER_NOT_FOUND.getMessage())); } diff --git a/src/main/java/com/diareat/diareat/user/service/UserService.java b/src/main/java/com/diareat/diareat/user/service/UserService.java index 259b749..965e9c7 100644 --- a/src/main/java/com/diareat/diareat/user/service/UserService.java +++ b/src/main/java/com/diareat/diareat/user/service/UserService.java @@ -42,7 +42,8 @@ public Long saveUser(CreateUserDto createUserDto) { throw new UserException(ResponseCode.USER_NAME_ALREADY_EXIST); } if (userRepository.existsByKeyCode(createUserDto.getKeyCode())) { - log.info("이미 존재하는 키코드입니다 by {}", createUserDto.getKeyCode()); + log.info("이미 존재하는 " + + "con키코드입니다 by {}", createUserDto.getKeyCode()); throw new UserException(ResponseCode.USER_ALREADY_EXIST); }