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

feat: JWT access/refresh token #13

Merged
merged 5 commits into from
May 21, 2024
Merged
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
8 changes: 8 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ dependencies {
implementation group: 'org.postgresql', name: 'postgresql', version: '42.2.27'
runtimeOnly 'org.postgresql:postgresql'
runtimeOnly 'com.h2database:h2'
// cache
implementation 'org.springframework.boot:spring-boot-starter-data-redis'

// hibernate-spatial
implementation 'org.hibernate:hibernate-spatial:6.1.7.Final'
Expand All @@ -63,6 +65,10 @@ dependencies {
asciidoctorExt 'org.springframework.restdocs:spring-restdocs-asciidoctor'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'

//JWT
implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.2'
implementation group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.2'
implementation group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.2'
}

tasks.named('test') {
Expand Down Expand Up @@ -123,6 +129,8 @@ private excludedClassFilesForReport(classDirectories) {
"**/scheduler/**",
"**/global/**",
"**/common/**",
"**/*JwtService*",
"**/*TokenCacheService*"
])
})
)
Expand Down
97 changes: 97 additions & 0 deletions src/main/java/com/lovemarker/domain/auth/service/JwtService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package com.lovemarker.domain.auth.service;

import com.lovemarker.global.constant.TokenStatus;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Base64;
import java.util.Date;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class JwtService {

@Value("${jwt.secret}")
private String jwtSecret;

private static final long ACCESS_TOKEN_EXPIRY_TIME = 1000L * 60 * 60 * 2; // 2시간
private static final long REFRESH_TOKEN_EXPIRY_TIME = 1000L * 60 * 60 * 24 * 14; // 2주
private static final String CLAIM_NAME = "userId";
private final TokenCacheService tokenCacheService;

@PostConstruct
protected void init() {
jwtSecret = Base64.getEncoder()
.encodeToString(jwtSecret.getBytes(StandardCharsets.UTF_8));
}

// Access Token 발급
public String issuedAccessToken(Long userId) {
return issuedToken("access_token", ACCESS_TOKEN_EXPIRY_TIME, userId.toString());
}

// Refresh Token 발급
public String issuedRefreshToken(Long userId) {
String refreshToken = issuedToken("refresh_token", REFRESH_TOKEN_EXPIRY_TIME, userId.toString());
tokenCacheService.setValues(String.valueOf(userId), refreshToken, REFRESH_TOKEN_EXPIRY_TIME);
return refreshToken;
}

// JWT 토큰 발급
public String issuedToken(String tokenName, long expiryTime, String userId) {
final Date now = new Date();

final Claims claims = Jwts.claims()
.setSubject(tokenName)
.setIssuedAt(now)
.setExpiration(new Date(now.getTime() + expiryTime));

claims.put(CLAIM_NAME, userId);

return Jwts.builder()
.setHeaderParam(Header.TYPE, Header.JWT_TYPE)
.setClaims(claims)
.signWith(getSigningKey())
.compact();
}

private Key getSigningKey() {
final byte[] keyBytes = jwtSecret.getBytes(StandardCharsets.UTF_8);
return Keys.hmacShaKeyFor(keyBytes);
}

// JWT 토큰 검증
public long verifyToken(String token) {
try {
final Claims claims = getBody(token);
return TokenStatus.TOKEN_VALID;
} catch (RuntimeException e) {
if (e instanceof ExpiredJwtException) {
return TokenStatus.TOKEN_EXPIRED;
}
return TokenStatus.TOKEN_INVALID;
}
}

private Claims getBody(final String token) {
return Jwts.parserBuilder()
.setSigningKey(getSigningKey())
.build()
.parseClaimsJws(token)
.getBody();
}

// JWT 토큰 내용 확인
public String getJwtContents(String token) {
final Claims claims = getBody(token);
return (String) claims.get(CLAIM_NAME);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.lovemarker.domain.auth.service;

import java.time.Duration;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class TokenCacheService {

private final RedisTemplate<String, String> redisTemplate;

public void setValues(String key, String value, long expiryTime){
redisTemplate.opsForValue().set(key, value, Duration.ofMillis(expiryTime));
}

public String getValuesByKey(String key){
return redisTemplate.opsForValue().get(key);
}

public void deleteValueByKey(String key){
redisTemplate.delete(key);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
import com.lovemarker.domain.couple.dto.request.JoinCoupleRequest;
import com.lovemarker.domain.couple.dto.response.CreateInvitationCodeResponse;
import com.lovemarker.domain.couple.service.CoupleService;
import com.lovemarker.global.config.resolver.UserId;
import com.lovemarker.global.constant.SuccessCode;
import com.lovemarker.global.dto.ApiResponseDto;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

Expand All @@ -23,7 +23,7 @@ public class CoupleController {

@PostMapping
public ApiResponseDto<CreateInvitationCodeResponse> createInvitationCode(
@RequestHeader Long userId,
@UserId Long userId,
@Valid @RequestBody final CreateInvitationCodeRequest createInvitationCodeRequest
) {
return ApiResponseDto.success(SuccessCode.CREATE_INVITATION_CODE_SUCCESS,
Expand All @@ -32,7 +32,7 @@ public ApiResponseDto<CreateInvitationCodeResponse> createInvitationCode(

@PostMapping("/join")
public ApiResponseDto joinCouple(
@RequestHeader Long userId,
@UserId Long userId,
@Valid @RequestBody final JoinCoupleRequest joinCoupleRequest
) {
coupleService.joinCouple(userId, joinCoupleRequest.invitationCode());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.lovemarker.domain.user.exception;

import com.lovemarker.global.constant.ErrorCode;
import com.lovemarker.global.exception.BasicException;

public class InvalidAccessTokenException extends BasicException {

public InvalidAccessTokenException(ErrorCode errorCode, String message) {
super(errorCode, message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.lovemarker.domain.user.exception;

import com.lovemarker.global.constant.ErrorCode;
import com.lovemarker.global.exception.BasicException;

public class NullAccessTokenException extends BasicException {

public NullAccessTokenException(ErrorCode errorCode, String message) {
super(errorCode, message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.lovemarker.domain.user.exception;

import com.lovemarker.global.constant.ErrorCode;
import com.lovemarker.global.exception.BasicException;

public class TimeExpiredAccessTokenException extends BasicException {

public TimeExpiredAccessTokenException(ErrorCode errorCode, String message) {
super(errorCode, message);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.lovemarker.domain.user.exception;

import com.lovemarker.global.constant.ErrorCode;
import com.lovemarker.global.exception.NotFoundException;

public class UserNotFoundException extends NotFoundException {

public UserNotFoundException(ErrorCode errorCode, String message) {
super(errorCode, message);
}
}
32 changes: 32 additions & 0 deletions src/main/java/com/lovemarker/global/config/RedisConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.lovemarker.global.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
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.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;

@EnableCaching
@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 ListOperations<String, String> listOperations(
RedisTemplate<String, String> redisStringTemplate) {
return redisStringTemplate.opsForList();
}
}
20 changes: 20 additions & 0 deletions src/main/java/com/lovemarker/global/config/WebConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.lovemarker.global.config;

import com.lovemarker.global.config.resolver.UserIdResolver;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {

private final UserIdResolver userIdResolver;

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(userIdResolver);
}
}
11 changes: 11 additions & 0 deletions src/main/java/com/lovemarker/global/config/resolver/UserId.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.lovemarker.global.config.resolver;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface UserId {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.lovemarker.global.config.resolver;

import com.lovemarker.domain.auth.service.JwtService;
import com.lovemarker.domain.user.exception.InvalidAccessTokenException;
import com.lovemarker.domain.user.exception.NullAccessTokenException;
import com.lovemarker.domain.user.exception.TimeExpiredAccessTokenException;
import com.lovemarker.domain.user.exception.UserNotFoundException;
import com.lovemarker.global.constant.ErrorCode;
import com.lovemarker.global.constant.TokenStatus;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Component
@RequiredArgsConstructor
public class UserIdResolver implements HandlerMethodArgumentResolver {
private final JwtService jwtService;

@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.hasParameterAnnotation(UserId.class) && Long.class.equals(parameter.getParameterType());
}

@Override
public Object resolveArgument(@NotNull MethodParameter parameter, ModelAndViewContainer modelAndViewContainer, @NotNull NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
final HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
String accessToken = request.getHeader("accessToken");
String refreshToken = request.getHeader("refreshToken");

if (accessToken == null || refreshToken == null) {
throw new NullAccessTokenException(ErrorCode.NULL_ACCESS_TOKEN_EXCEPTION, ErrorCode.NULL_ACCESS_TOKEN_EXCEPTION.getMessage());
}

// 토큰 검증
if (jwtService.verifyToken(accessToken) == TokenStatus.TOKEN_EXPIRED) {
throw new TimeExpiredAccessTokenException(ErrorCode.ACCESS_TOKEN_TIME_EXPIRED_EXCEPTION, ErrorCode.ACCESS_TOKEN_TIME_EXPIRED_EXCEPTION.getMessage());
} else if (jwtService.verifyToken(accessToken) == TokenStatus.TOKEN_INVALID) {
throw new InvalidAccessTokenException(ErrorCode.INVALID_ACCESS_TOKEN_EXCEPTION, ErrorCode.INVALID_ACCESS_TOKEN_EXCEPTION.getMessage());
}

// 유저 아이디 반환
final String tokenContents = jwtService.getJwtContents(accessToken);

try {
return Long.parseLong(tokenContents);
} catch (NumberFormatException e) {
throw new UserNotFoundException(ErrorCode.NOT_FOUND_USER_EXCEPTION, ErrorCode.NOT_FOUND_USER_EXCEPTION.getMessage());
}
}
}
8 changes: 8 additions & 0 deletions src/main/java/com/lovemarker/global/constant/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,17 @@ public enum ErrorCode {
REQUEST_VALIDATION_EXCEPTION(HttpStatus.BAD_REQUEST, "잘못된 요청입니다."),
MISSING_REQUIRED_INFO_EXCEPTION(HttpStatus.BAD_REQUEST, "필수 입력 항목이 입력되지 않았습니다."),
MISSING_REQUIRED_HEADER_EXCEPTION(HttpStatus.BAD_REQUEST, "필수 입력 헤더 정보가 입력되지 않았습니다."),
NULL_ACCESS_TOKEN_EXCEPTION(HttpStatus.BAD_REQUEST, "토큰 값이 없습니다."),

// 401
ACCESS_TOKEN_TIME_EXPIRED_EXCEPTION(HttpStatus.UNAUTHORIZED, "만료된 토큰입니다."),
REFRESH_TOKEN_TIME_EXPIRED_EXCEPTION(HttpStatus.UNAUTHORIZED, "만료된 토큰입니다."),
INVALID_REFRESH_TOKEN_EXCEPTION(HttpStatus.UNAUTHORIZED, "유효하지 않은 리프레시 토큰입니다."),
INVALID_ACCESS_TOKEN_EXCEPTION(HttpStatus.UNAUTHORIZED, "유효하지 않은 엑세스 토큰입니다."),

// 404
NOT_FOUND_EXCEPTION(HttpStatus.NOT_FOUND, "존재하지 않는 리소스입니다."),
NOT_FOUND_USER_EXCEPTION(HttpStatus.NOT_FOUND, "존재하지 않는 유저입니다"),

// 500
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "서버 내부 오류 발생");
Expand Down
13 changes: 13 additions & 0 deletions src/main/java/com/lovemarker/global/constant/TokenStatus.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.lovemarker.global.constant;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class TokenStatus {
public static final long TOKEN_EXPIRED = -99;
public static final long TOKEN_INVALID = -98;
public static final long TOKEN_VALID = -97;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.lovemarker.global.constant.ErrorCode;

public class NotFoundException extends BasicException {

public NotFoundException(ErrorCode errorCode, String message) {
super(errorCode, message);
}
Expand Down
Loading
Loading