mirror of
https://github.com/won-ktds/smarketing-backend.git
synced 2026-06-13 04:49:10 +00:00
add: init project
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
dependencies {
|
||||
api 'org.springframework.boot:spring-boot-starter-web'
|
||||
api 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
api 'org.springframework.boot:spring-boot-starter-security'
|
||||
api 'org.springframework.boot:spring-boot-starter-validation'
|
||||
api 'org.springframework.boot:spring-boot-starter-data-redis'
|
||||
api 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.2.0'
|
||||
api 'io.jsonwebtoken:jjwt-api:0.12.3'
|
||||
api 'io.jsonwebtoken:jjwt-impl:0.12.3'
|
||||
api 'io.jsonwebtoken:jjwt-jackson:0.12.3'
|
||||
api 'org.projectlombok:lombok'
|
||||
}
|
||||
|
||||
jar {
|
||||
enabled = true
|
||||
archiveClassifier = ''
|
||||
}
|
||||
|
||||
bootJar {
|
||||
enabled = false
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Spring Security 설정 클래스
|
||||
* 인증, 인가, CORS 등 보안 관련 설정
|
||||
* JWT 기반 인증 및 CORS 설정
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@@ -30,17 +30,7 @@ public class SecurityConfig {
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
|
||||
/**
|
||||
* 패스워드 인코더 Bean 설정
|
||||
*
|
||||
* @return BCrypt 패스워드 인코더
|
||||
*/
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Security Filter Chain 설정
|
||||
* Spring Security 필터 체인 설정
|
||||
*
|
||||
* @param http HttpSecurity 객체
|
||||
* @return SecurityFilterChain
|
||||
@@ -49,43 +39,43 @@ public class SecurityConfig {
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.sessionManagement(session ->
|
||||
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers(
|
||||
"/api/member/register",
|
||||
"/api/member/check-duplicate",
|
||||
"/api/member/validate-password",
|
||||
"/api/auth/login",
|
||||
"/swagger-ui/**",
|
||||
"/swagger-ui.html",
|
||||
"/api-docs/**",
|
||||
"/actuator/**"
|
||||
).permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/api/auth/**", "/api/member/register", "/api/member/check-duplicate/**",
|
||||
"/api/member/validate-password", "/swagger-ui/**", "/v3/api-docs/**",
|
||||
"/swagger-resources/**", "/webjars/**").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 패스워드 인코더 빈 등록
|
||||
*
|
||||
* @return BCryptPasswordEncoder
|
||||
*/
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
/**
|
||||
* CORS 설정
|
||||
*
|
||||
* @return CORS 설정 소스
|
||||
* @return CorsConfigurationSource
|
||||
*/
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
configuration.setAllowedOriginPatterns(Arrays.asList("*"));
|
||||
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
|
||||
configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
|
||||
configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
|
||||
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
|
||||
configuration.setAllowedHeaders(Arrays.asList("*"));
|
||||
configuration.setAllowCredentials(true);
|
||||
configuration.setMaxAge(3600L);
|
||||
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", configuration);
|
||||
return source;
|
||||
|
||||
@@ -9,8 +9,8 @@ import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Swagger 설정 클래스
|
||||
* API 문서화를 위한 OpenAPI 설정
|
||||
* Swagger OpenAPI 설정 클래스
|
||||
* API 문서화 및 JWT 인증 설정
|
||||
*/
|
||||
@Configuration
|
||||
public class SwaggerConfig {
|
||||
@@ -18,24 +18,26 @@ public class SwaggerConfig {
|
||||
/**
|
||||
* OpenAPI 설정
|
||||
*
|
||||
* @return OpenAPI 인스턴스
|
||||
* @return OpenAPI 객체
|
||||
*/
|
||||
@Bean
|
||||
public OpenAPI openAPI() {
|
||||
String securitySchemeName = "bearerAuth";
|
||||
String jwtSchemeName = "jwtAuth";
|
||||
SecurityRequirement securityRequirement = new SecurityRequirement().addList(jwtSchemeName);
|
||||
|
||||
Components components = new Components()
|
||||
.addSecuritySchemes(jwtSchemeName, new SecurityScheme()
|
||||
.name(jwtSchemeName)
|
||||
.type(SecurityScheme.Type.HTTP)
|
||||
.scheme("bearer")
|
||||
.bearerFormat("JWT"));
|
||||
|
||||
return new OpenAPI()
|
||||
.info(new Info()
|
||||
.title("AI 마케팅 서비스 API")
|
||||
.description("소상공인을 위한 맞춤형 AI 마케팅 솔루션 API 문서")
|
||||
.version("v1.0.0"))
|
||||
.addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
|
||||
.components(new Components()
|
||||
.addSecuritySchemes(securitySchemeName,
|
||||
new SecurityScheme()
|
||||
.name(securitySchemeName)
|
||||
.type(SecurityScheme.Type.HTTP)
|
||||
.scheme("bearer")
|
||||
.bearerFormat("JWT")));
|
||||
.title("스마케팅 API")
|
||||
.description("소상공인을 위한 AI 마케팅 서비스 API")
|
||||
.version("1.0.0"))
|
||||
.addSecurityItem(securityRequirement)
|
||||
.components(components);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,22 +9,22 @@ import lombok.NoArgsConstructor;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 페이지네이션 응답 DTO
|
||||
* 페이지 단위 조회 결과를 담는 공통 형식
|
||||
* 페이징 응답 DTO
|
||||
* 페이징된 데이터 응답에 사용되는 공통 형식
|
||||
*
|
||||
* @param <T> 페이지 내용의 데이터 타입
|
||||
* @param <T> 응답 데이터 타입
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
@Schema(description = "페이지네이션 응답")
|
||||
@Schema(description = "페이징 응답")
|
||||
public class PageResponse<T> {
|
||||
|
||||
@Schema(description = "페이지 내용")
|
||||
@Schema(description = "페이지 컨텐츠", example = "[...]")
|
||||
private List<T> content;
|
||||
|
||||
@Schema(description = "현재 페이지 번호", example = "0")
|
||||
@Schema(description = "페이지 번호 (0부터 시작)", example = "0")
|
||||
private int pageNumber;
|
||||
|
||||
@Schema(description = "페이지 크기", example = "20")
|
||||
@@ -41,4 +41,28 @@ public class PageResponse<T> {
|
||||
|
||||
@Schema(description = "마지막 페이지 여부", example = "false")
|
||||
private boolean last;
|
||||
|
||||
/**
|
||||
* 성공적인 페이징 응답 생성
|
||||
*
|
||||
* @param content 페이지 컨텐츠
|
||||
* @param pageNumber 페이지 번호
|
||||
* @param pageSize 페이지 크기
|
||||
* @param totalElements 전체 요소 수
|
||||
* @param <T> 데이터 타입
|
||||
* @return 페이징 응답
|
||||
*/
|
||||
public static <T> PageResponse<T> of(List<T> content, int pageNumber, int pageSize, long totalElements) {
|
||||
int totalPages = (int) Math.ceil((double) totalElements / pageSize);
|
||||
|
||||
return PageResponse.<T>builder()
|
||||
.content(content)
|
||||
.pageNumber(pageNumber)
|
||||
.pageSize(pageSize)
|
||||
.totalElements(totalElements)
|
||||
.totalPages(totalPages)
|
||||
.first(pageNumber == 0)
|
||||
.last(pageNumber >= totalPages - 1)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
+33
-105
@@ -2,21 +2,18 @@ package com.won.smarketing.common.exception;
|
||||
|
||||
import com.won.smarketing.common.dto.ApiResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
|
||||
import java.nio.file.AccessDeniedException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 전역 예외 처리 핸들러
|
||||
* 애플리케이션에서 발생하는 모든 예외를 처리하여 일관된 응답 형식 제공
|
||||
* 전역 예외 처리기
|
||||
* 애플리케이션 전반의 예외를 통일된 형식으로 처리
|
||||
*/
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
@@ -31,121 +28,52 @@ public class GlobalExceptionHandler {
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleBusinessException(BusinessException ex) {
|
||||
log.warn("Business exception occurred: {}", ex.getMessage());
|
||||
ErrorCode errorCode = ex.getErrorCode();
|
||||
|
||||
return ResponseEntity
|
||||
.status(errorCode.getHttpStatus())
|
||||
.body(ApiResponse.error(errorCode.getHttpStatus().value(), ex.getMessage()));
|
||||
.status(ex.getErrorCode().getHttpStatus())
|
||||
.body(ApiResponse.error(
|
||||
ex.getErrorCode().getHttpStatus().value(),
|
||||
ex.getMessage()
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효성 검증 예외 처리 (@Valid 애노테이션)
|
||||
* 입력값 검증 예외 처리
|
||||
*
|
||||
* @param ex 유효성 검증 예외
|
||||
* @param ex 입력값 검증 예외
|
||||
* @return 오류 응답
|
||||
*/
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleValidationException(MethodArgumentNotValidException ex) {
|
||||
public ResponseEntity<ApiResponse<Map<String, String>>> handleValidationException(
|
||||
MethodArgumentNotValidException ex) {
|
||||
log.warn("Validation exception occurred: {}", ex.getMessage());
|
||||
String errorMessage = ex.getBindingResult()
|
||||
.getFieldErrors()
|
||||
.stream()
|
||||
.findFirst()
|
||||
.map(error -> error.getDefaultMessage())
|
||||
.orElse("유효성 검증에 실패했습니다.");
|
||||
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error(HttpStatus.BAD_REQUEST.value(), errorMessage));
|
||||
Map<String, String> errors = new HashMap<>();
|
||||
ex.getBindingResult().getAllErrors().forEach(error -> {
|
||||
String fieldName = ((FieldError) error).getField();
|
||||
String errorMessage = error.getDefaultMessage();
|
||||
errors.put(fieldName, errorMessage);
|
||||
});
|
||||
|
||||
return ResponseEntity.badRequest()
|
||||
.body(ApiResponse.<Map<String, String>>builder()
|
||||
.status(400)
|
||||
.message("입력값 검증에 실패했습니다.")
|
||||
.data(errors)
|
||||
.build());
|
||||
}
|
||||
|
||||
/**
|
||||
* 바인딩 예외 처리
|
||||
*
|
||||
* @param ex 바인딩 예외
|
||||
* @return 오류 응답
|
||||
*/
|
||||
@ExceptionHandler(BindException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleBindException(BindException ex) {
|
||||
log.warn("Bind exception occurred: {}", ex.getMessage());
|
||||
String errorMessage = ex.getBindingResult()
|
||||
.getFieldErrors()
|
||||
.stream()
|
||||
.findFirst()
|
||||
.map(error -> error.getDefaultMessage())
|
||||
.orElse("요청 데이터 바인딩에 실패했습니다.");
|
||||
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error(HttpStatus.BAD_REQUEST.value(), errorMessage));
|
||||
}
|
||||
|
||||
/**
|
||||
* 타입 불일치 예외 처리
|
||||
*
|
||||
* @param ex 타입 불일치 예외
|
||||
* @return 오류 응답
|
||||
*/
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleTypeMismatchException(MethodArgumentTypeMismatchException ex) {
|
||||
log.warn("Type mismatch exception occurred: {}", ex.getMessage());
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error(HttpStatus.BAD_REQUEST.value(), "잘못된 타입의 값입니다."));
|
||||
}
|
||||
|
||||
/**
|
||||
* 필수 파라미터 누락 예외 처리
|
||||
*
|
||||
* @param ex 필수 파라미터 누락 예외
|
||||
* @return 오류 응답
|
||||
*/
|
||||
@ExceptionHandler(MissingServletRequestParameterException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleMissingParameterException(MissingServletRequestParameterException ex) {
|
||||
log.warn("Missing parameter exception occurred: {}", ex.getMessage());
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.body(ApiResponse.error(HttpStatus.BAD_REQUEST.value(), "필수 요청 파라미터가 누락되었습니다: " + ex.getParameterName()));
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP 메서드 불일치 예외 처리
|
||||
*
|
||||
* @param ex HTTP 메서드 불일치 예외
|
||||
* @return 오류 응답
|
||||
*/
|
||||
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
|
||||
log.warn("Method not supported exception occurred: {}", ex.getMessage());
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.METHOD_NOT_ALLOWED)
|
||||
.body(ApiResponse.error(HttpStatus.METHOD_NOT_ALLOWED.value(), "허용되지 않은 HTTP 메서드입니다."));
|
||||
}
|
||||
|
||||
/**
|
||||
* 접근 거부 예외 처리
|
||||
*
|
||||
* @param ex 접근 거부 예외
|
||||
* @return 오류 응답
|
||||
*/
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleAccessDeniedException(AccessDeniedException ex) {
|
||||
log.warn("Access denied exception occurred: {}", ex.getMessage());
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.FORBIDDEN)
|
||||
.body(ApiResponse.error(HttpStatus.FORBIDDEN.value(), "접근이 거부되었습니다."));
|
||||
}
|
||||
|
||||
/**
|
||||
* 기타 모든 예외 처리
|
||||
* 일반적인 예외 처리
|
||||
*
|
||||
* @param ex 예외
|
||||
* @return 오류 응답
|
||||
*/
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ApiResponse<Void>> handleGenericException(Exception ex) {
|
||||
public ResponseEntity<ApiResponse<Void>> handleException(Exception ex) {
|
||||
log.error("Unexpected exception occurred", ex);
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(ApiResponse.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "서버 내부 오류가 발생했습니다."));
|
||||
|
||||
return ResponseEntity.internalServerError()
|
||||
.body(ApiResponse.error(500, "서버 내부 오류가 발생했습니다."));
|
||||
}
|
||||
}
|
||||
|
||||
+27
-18
@@ -7,8 +7,8 @@ import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
@@ -18,7 +18,7 @@ import java.util.Collections;
|
||||
|
||||
/**
|
||||
* JWT 인증 필터
|
||||
* 요청 헤더에서 JWT 토큰을 추출하여 인증 처리
|
||||
* HTTP 요청에서 JWT 토큰을 추출하고 인증 처리
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -30,44 +30,53 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
private static final String BEARER_PREFIX = "Bearer ";
|
||||
|
||||
/**
|
||||
* JWT 토큰 인증 처리
|
||||
* JWT 토큰 기반 인증 필터링
|
||||
*
|
||||
* @param request HTTP 요청
|
||||
* @param response HTTP 응답
|
||||
* @param filterChain 필터 체인
|
||||
* @throws ServletException 서블릿 예외
|
||||
* @throws IOException I/O 예외
|
||||
* @throws IOException IO 예외
|
||||
*/
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
protected void doFilterInternal(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain) throws ServletException, IOException {
|
||||
|
||||
// 요청 헤더에서 JWT 토큰 추출
|
||||
String token = resolveToken(request);
|
||||
|
||||
// 토큰이 있고 유효한 경우 인증 정보 설정
|
||||
if (StringUtils.hasText(token) && jwtTokenProvider.validateToken(token)) {
|
||||
String userId = jwtTokenProvider.getUserIdFromToken(token);
|
||||
Authentication authentication = new UsernamePasswordAuthenticationToken(
|
||||
userId, null, Collections.emptyList());
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
log.debug("Security context에 '{}' 인증 정보를 저장했습니다.", userId);
|
||||
try {
|
||||
String jwt = getJwtFromRequest(request);
|
||||
|
||||
if (StringUtils.hasText(jwt) && jwtTokenProvider.validateToken(jwt)) {
|
||||
String userId = jwtTokenProvider.getUserIdFromToken(jwt);
|
||||
|
||||
// 사용자 인증 정보 설정
|
||||
UsernamePasswordAuthenticationToken authentication =
|
||||
new UsernamePasswordAuthenticationToken(userId, null, Collections.emptyList());
|
||||
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
log.debug("User '{}' authenticated successfully", userId);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.error("Could not set user authentication in security context", ex);
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 요청 헤더에서 JWT 토큰 추출
|
||||
* HTTP 요청에서 JWT 토큰 추출
|
||||
*
|
||||
* @param request HTTP 요청
|
||||
* @return JWT 토큰 (Bearer 접두사 제거)
|
||||
* @return JWT 토큰 (Bearer 접두사 제거된)
|
||||
*/
|
||||
private String resolveToken(HttpServletRequest request) {
|
||||
private String getJwtFromRequest(HttpServletRequest request) {
|
||||
String bearerToken = request.getHeader(AUTHORIZATION_HEADER);
|
||||
|
||||
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(BEARER_PREFIX)) {
|
||||
return bearerToken.substring(BEARER_PREFIX.length());
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
package com.won.smarketing.common.security;
|
||||
|
||||
import com.won.smarketing.common.exception.BusinessException;
|
||||
import com.won.smarketing.common.exception.ErrorCode;
|
||||
import io.jsonwebtoken.*;
|
||||
import io.jsonwebtoken.io.Decoders;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
@@ -13,67 +10,65 @@ import javax.crypto.SecretKey;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* JWT 토큰 생성 및 검증 유틸리티
|
||||
* Access Token과 Refresh Token 관리
|
||||
* JWT 토큰 생성 및 검증을 담당하는 클래스
|
||||
* 액세스 토큰과 리프레시 토큰의 생성, 검증, 파싱 기능 제공
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class JwtTokenProvider {
|
||||
|
||||
private final SecretKey key;
|
||||
private final SecretKey secretKey;
|
||||
private final long accessTokenValidityTime;
|
||||
private final long refreshTokenValidityTime;
|
||||
|
||||
/**
|
||||
* JWT 토큰 프로바이더 생성자
|
||||
*
|
||||
* @param secretKey JWT 서명에 사용할 비밀키
|
||||
* @param accessTokenValidityTime Access Token 유효 시간 (밀리초)
|
||||
* @param refreshTokenValidityTime Refresh Token 유효 시간 (밀리초)
|
||||
* @param secret JWT 서명에 사용할 비밀키
|
||||
* @param accessTokenValidityTime 액세스 토큰 유효시간 (밀리초)
|
||||
* @param refreshTokenValidityTime 리프레시 토큰 유효시간 (밀리초)
|
||||
*/
|
||||
public JwtTokenProvider(
|
||||
@Value("${jwt.secret-key}") String secretKey,
|
||||
@Value("${jwt.access-token-validity}") long accessTokenValidityTime,
|
||||
@Value("${jwt.refresh-token-validity}") long refreshTokenValidityTime) {
|
||||
byte[] keyBytes = Decoders.BASE64.decode(secretKey);
|
||||
this.key = Keys.hmacShaKeyFor(keyBytes);
|
||||
public JwtTokenProvider(@Value("${jwt.secret}") String secret,
|
||||
@Value("${jwt.access-token-validity}") long accessTokenValidityTime,
|
||||
@Value("${jwt.refresh-token-validity}") long refreshTokenValidityTime) {
|
||||
this.secretKey = Keys.hmacShaKeyFor(secret.getBytes());
|
||||
this.accessTokenValidityTime = accessTokenValidityTime;
|
||||
this.refreshTokenValidityTime = refreshTokenValidityTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Access Token 생성
|
||||
* 액세스 토큰 생성
|
||||
*
|
||||
* @param userId 사용자 ID
|
||||
* @return Access Token
|
||||
* @return 생성된 액세스 토큰
|
||||
*/
|
||||
public String generateAccessToken(String userId) {
|
||||
long now = System.currentTimeMillis();
|
||||
Date validity = new Date(now + accessTokenValidityTime);
|
||||
Date now = new Date();
|
||||
Date expiryDate = new Date(now.getTime() + accessTokenValidityTime);
|
||||
|
||||
return Jwts.builder()
|
||||
.setSubject(userId)
|
||||
.setIssuedAt(new Date(now))
|
||||
.setExpiration(validity)
|
||||
.signWith(key, SignatureAlgorithm.HS256)
|
||||
.setIssuedAt(now)
|
||||
.setExpiration(expiryDate)
|
||||
.signWith(secretKey)
|
||||
.compact();
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh Token 생성
|
||||
* 리프레시 토큰 생성
|
||||
*
|
||||
* @param userId 사용자 ID
|
||||
* @return Refresh Token
|
||||
* @return 생성된 리프레시 토큰
|
||||
*/
|
||||
public String generateRefreshToken(String userId) {
|
||||
long now = System.currentTimeMillis();
|
||||
Date validity = new Date(now + refreshTokenValidityTime);
|
||||
Date now = new Date();
|
||||
Date expiryDate = new Date(now.getTime() + refreshTokenValidityTime);
|
||||
|
||||
return Jwts.builder()
|
||||
.setSubject(userId)
|
||||
.setIssuedAt(new Date(now))
|
||||
.setExpiration(validity)
|
||||
.signWith(key, SignatureAlgorithm.HS256)
|
||||
.setIssuedAt(now)
|
||||
.setExpiration(expiryDate)
|
||||
.signWith(secretKey)
|
||||
.compact();
|
||||
}
|
||||
|
||||
@@ -84,67 +79,48 @@ public class JwtTokenProvider {
|
||||
* @return 사용자 ID
|
||||
*/
|
||||
public String getUserIdFromToken(String token) {
|
||||
Claims claims = parseClaims(token);
|
||||
Claims claims = Jwts.parserBuilder()
|
||||
.setSigningKey(secretKey)
|
||||
.build()
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
|
||||
return claims.getSubject();
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰 유효성 검증
|
||||
*
|
||||
* @param token JWT 토큰
|
||||
* @param token 검증할 토큰
|
||||
* @return 유효성 여부
|
||||
*/
|
||||
public boolean validateToken(String token) {
|
||||
try {
|
||||
parseClaims(token);
|
||||
Jwts.parserBuilder()
|
||||
.setSigningKey(secretKey)
|
||||
.build()
|
||||
.parseClaimsJws(token);
|
||||
return true;
|
||||
} catch (ExpiredJwtException e) {
|
||||
log.warn("Expired JWT token: {}", e.getMessage());
|
||||
throw new BusinessException(ErrorCode.TOKEN_EXPIRED);
|
||||
} catch (UnsupportedJwtException e) {
|
||||
log.warn("Unsupported JWT token: {}", e.getMessage());
|
||||
throw new BusinessException(ErrorCode.INVALID_TOKEN);
|
||||
} catch (MalformedJwtException e) {
|
||||
log.warn("Malformed JWT token: {}", e.getMessage());
|
||||
throw new BusinessException(ErrorCode.INVALID_TOKEN);
|
||||
} catch (SecurityException e) {
|
||||
log.warn("Invalid JWT signature: {}", e.getMessage());
|
||||
throw new BusinessException(ErrorCode.INVALID_TOKEN);
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.warn("JWT token compact of handler are invalid: {}", e.getMessage());
|
||||
throw new BusinessException(ErrorCode.INVALID_TOKEN);
|
||||
} catch (SecurityException ex) {
|
||||
log.error("Invalid JWT signature: {}", ex.getMessage());
|
||||
} catch (MalformedJwtException ex) {
|
||||
log.error("Invalid JWT token: {}", ex.getMessage());
|
||||
} catch (ExpiredJwtException ex) {
|
||||
log.error("Expired JWT token: {}", ex.getMessage());
|
||||
} catch (UnsupportedJwtException ex) {
|
||||
log.error("Unsupported JWT token: {}", ex.getMessage());
|
||||
} catch (IllegalArgumentException ex) {
|
||||
log.error("JWT claims string is empty: {}", ex.getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 토큰에서 Claims 추출
|
||||
* 액세스 토큰 유효시간 반환
|
||||
*
|
||||
* @param token JWT 토큰
|
||||
* @return Claims
|
||||
*/
|
||||
private Claims parseClaims(String token) {
|
||||
return Jwts.parserBuilder()
|
||||
.setSigningKey(key)
|
||||
.build()
|
||||
.parseClaimsJws(token)
|
||||
.getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* Access Token 유효 시간 반환
|
||||
*
|
||||
* @return Access Token 유효 시간 (밀리초)
|
||||
* @return 액세스 토큰 유효시간 (밀리초)
|
||||
*/
|
||||
public long getAccessTokenValidityTime() {
|
||||
return accessTokenValidityTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh Token 유효 시간 반환
|
||||
*
|
||||
* @return Refresh Token 유효 시간 (밀리초)
|
||||
*/
|
||||
public long getRefreshTokenValidityTime() {
|
||||
return refreshTokenValidityTime;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user