Skip to content
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

#6 - 6차 세미나 실습 과제 제출 #6

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package org.sopt.springPractice.auth.redis.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

@Value("${spring.data.redis.host}")
private String host;

@Value("${spring.data.redis.port}")
private int port;

@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(host, port);
}

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

return template;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.sopt.springPractice.auth.redis.controller;

import lombok.RequiredArgsConstructor;
import org.sopt.springPractice.auth.PrincipalHandler;
import org.sopt.springPractice.auth.redis.service.TokenService;
import org.sopt.springPractice.auth.redis.service.dto.AccessTokenDTO;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Transactional
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/token")
public class TokenController {

private final TokenService tokenService;
private final PrincipalHandler principalHandler;

@PostMapping("/reissue")
public ResponseEntity<AccessTokenDTO> reissueAccessToken() {
Long userId = principalHandler.getUserIdFromPrincipal();
AccessTokenDTO newAccessTokenResponse = tokenService.reissueAccessToken(userId);

return ResponseEntity.status(HttpStatus.CREATED)
.body(newAccessTokenResponse);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;

@RedisHash(value = "", timeToLive = 60 * 60 * 24 * 1000L * 14)
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Builder
public class Token {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.sopt.springPractice.auth.redis.service;

import lombok.RequiredArgsConstructor;
import org.sopt.springPractice.auth.redis.domain.Token;
import org.sopt.springPractice.auth.redis.repository.RedisTokenRepository;
import org.sopt.springPractice.auth.redis.service.dto.AccessTokenDTO;
import org.sopt.springPractice.common.dto.ErrorMessage;
import org.sopt.springPractice.common.jwt.JwtTokenProvider;
import org.sopt.springPractice.exception.UnauthorizedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class TokenService {

private final RedisTokenRepository redisTokenRepository;
private final JwtTokenProvider jwtTokenProvider;

@Transactional
public AccessTokenDTO reissueAccessToken(Long userId) {
Token token = redisTokenRepository.findById(userId).orElseThrow(
() -> new UnauthorizedException(ErrorMessage.MEMBER_NOT_FOUND)
);

jwtTokenProvider.validateToken(token.getRefreshToken());
String newAccessToken = jwtTokenProvider.newAccessToken(token.getRefreshToken());

return AccessTokenDTO.of(newAccessToken);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package org.sopt.springPractice.auth.redis.service.dto;

public record AccessTokenDTO(
String accessToken
) {
public static AccessTokenDTO of(String accessToken) {
return new AccessTokenDTO(accessToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ public enum ErrorMessage {

MEMBER_NOT_FOUND(HttpStatus.NOT_FOUND.value(), "ID에 해당하는 사용자가 존재하지 않습니다."),
BLOG_NOT_FOUND(HttpStatus.NOT_FOUND.value(), "ID에 해당하는 블로그가 존재하지 않습니다."),
JWT_UNAUTHORIZED_EXCEPTION(HttpStatus.UNAUTHORIZED.value(), "사용자의 로그인 검증을 실패했습니다.");
JWT_UNAUTHORIZED_EXCEPTION(HttpStatus.UNAUTHORIZED.value(), "사용자의 로그인 검증을 실패했습니다."),
EXPIRED_JWT_TOKEN(HttpStatus.UNAUTHORIZED.value(), "만료된 refresh 토큰입니다.");
private final int status;
private final String message;
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import java.util.Date;
import javax.crypto.SecretKey;
import lombok.RequiredArgsConstructor;
import org.sopt.springPractice.auth.UserAuthentication;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
Expand All @@ -22,8 +23,8 @@ public class JwtTokenProvider {

private static final String USER_ID = "userId";

private static final Long ACCESS_TOKEN_EXPIRATION_TIME = 24 * 60 * 60 * 1000L * 14;
private static final Long REFRESH_TOKEN_EXPIRATION_TIME = 60 * 60 * 24 * 1000L * 14;
private static final Long ACCESS_TOKEN_EXPIRATION_TIME = 24 * 60 * 60 * 1000L * 2;
private static final Long REFRESH_TOKEN_EXPIRATION_TIME = 24 * 60 * 60 * 1000L * 14;

@Value("${jwt.secret}")
private String JWT_SECRET;
Expand Down Expand Up @@ -83,4 +84,12 @@ public Long getUserFromJwt(String token) {
Claims claims = getBody(token);
return Long.valueOf(claims.get(USER_ID).toString());
}

public String newAccessToken(String refreshToken) {
Claims claims = getBody(refreshToken);
Long userId = Long.valueOf(claims.get(USER_ID).toString());
Authentication authentication = UserAuthentication.createUserAuthentication(userId);

return issueAccessToken(authentication);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.sopt.springPractice.auth.UserAuthentication;
import org.sopt.springPractice.auth.redis.domain.Token;
import org.sopt.springPractice.auth.redis.repository.RedisTokenRepository;
import org.sopt.springPractice.common.dto.ErrorMessage;
import org.sopt.springPractice.common.jwt.JwtTokenProvider;
import org.sopt.springPractice.domain.Member;
Expand All @@ -21,6 +23,7 @@ public class MemberService {

private final MemberRepository memberRepository;
private final JwtTokenProvider jwtTokenProvider;
private final RedisTokenRepository redisTokenRepository;

@Transactional
public UserJoinResponse createMember(
Expand All @@ -33,8 +36,12 @@ public UserJoinResponse createMember(
String accessToken = jwtTokenProvider.issueAccessToken(
UserAuthentication.createUserAuthentication(memberId)
);
String refreshToken = jwtTokenProvider.issueRefreshToken(
UserAuthentication.createUserAuthentication(memberId)
);
redisTokenRepository.save(Token.of(memberId, refreshToken));

return UserJoinResponse.of(accessToken, memberId.toString());
return UserJoinResponse.of(accessToken, refreshToken, memberId.toString());
}

public Member findById(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

public record UserJoinResponse(
String accessToken,
String refreshToken,
String userId
) {
public static UserJoinResponse of(
String accessToken,
String refreshToken,
String userId
) {
return new UserJoinResponse(accessToken, userId);
return new UserJoinResponse(accessToken, refreshToken, userId);
}
}