From 16e2c858cff2a6c54b8cd5afb0568c749c59d6f9 Mon Sep 17 00:00:00 2001 From: ChaeAg Date: Thu, 21 Dec 2023 03:25:19 +0900 Subject: [PATCH] CI/CD Test --- ThirdSeminar/Dockerfile | 18 ++ ThirdSeminar/build.gradle | 13 +- .../seminar/config/BCryptPasswordConfig.java | 40 ++--- .../seminar/config/JpaAuditingConfig.java | 18 +- .../dosopt/seminar/config/SecurityConfig.java | 136 +++++++-------- .../config/jwt/CustomAccessDeniedHandler.java | 44 ++--- .../CustomJwtAuthenticationEntryPoint.java | 40 ++--- .../config/jwt/JwtAuthenticationFilter.java | 104 +++++------ .../seminar/config/jwt/JwtTokenProvider.java | 162 +++++++++--------- .../config/jwt/UserAuthentication.java | 28 +-- .../controller/ServiceMemberController.java | 64 +++---- .../seminar/service/ServiceMemberService.java | 78 ++++----- ThirdSeminar/src/main/resources/data.sql | 24 ++- 13 files changed, 394 insertions(+), 375 deletions(-) create mode 100644 ThirdSeminar/Dockerfile diff --git a/ThirdSeminar/Dockerfile b/ThirdSeminar/Dockerfile new file mode 100644 index 0000000..8599097 --- /dev/null +++ b/ThirdSeminar/Dockerfile @@ -0,0 +1,18 @@ +# baseimage -> 컨테이너의 내 에플리케이션이 돌아갈 수 있는 환경을 제공해주는 이미지 +# 현재는 애플리케이션을 실행할 수 있도록 amd64/amazoncorretto:17를 baseImage로 뒀는데요! +# amazoncorretto:17 이미지는 Linux를 base 이미지로 두고있기 때문에 +# amazoncorretto:17 이미지를 baseimage로 두면 linux에 JDK corretto 배포판이 설치된 환경이 제공됩니다. +FROM amd64/amazoncorretto:17 + +# baseimage를 바탕으로 다음 설정들을 진행하게 됩니다. + +# RUN, CMD, ENTRYPOINT 등 명령어들이 실행될 컨테이너 속 작업 디렉토리 설정 +WORKDIR /app + +# COPY {Dockerfile을 기준으로 container에 넣고자 하는 내용의 경로} {container내에 복사할 경로} +# host machine의 파일/디렉토리를 컨테이너 내 경로에 복사 +COPY ./build/libs/seminar-0.0.1-SNAPSHOT.jar /app/seminar.jar + +# 컨테이너가 실행될 때 실행할 명령어 지정 +# 위에서 workdir를 /app으로 지정해줬기 때문에 해당 명령어는 /app에서 실행됨 +CMD ["java", "-Duser.timezone=Asia/Seoul", "-jar", "seminar.jar"] \ No newline at end of file diff --git a/ThirdSeminar/build.gradle b/ThirdSeminar/build.gradle index e7caf80..307b995 100644 --- a/ThirdSeminar/build.gradle +++ b/ThirdSeminar/build.gradle @@ -33,16 +33,19 @@ dependencies { implementation 'mysql:mysql-connector-java:8.0.32' //security - implementation 'org.springframework.boot:spring-boot-starter-security' - testImplementation 'org.springframework.security:spring-security-test' +// implementation 'org.springframework.boot:spring-boot-starter-security' +// testImplementation 'org.springframework.security:spring-security-test' // AWS sdk implementation("software.amazon.awssdk:bom:2.21.0") implementation("software.amazon.awssdk:s3:2.21.0") - implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.5' - implementation group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.5' - implementation group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.5' +// implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.11.5' +// implementation group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.11.5' +// implementation group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: '0.11.5' + + // CI/CD 구축 + implementation 'org.springframework.boot:spring-boot-starter-actuator' } tasks.named('test') { diff --git a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/BCryptPasswordConfig.java b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/BCryptPasswordConfig.java index 15b2952..04d530e 100644 --- a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/BCryptPasswordConfig.java +++ b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/BCryptPasswordConfig.java @@ -1,20 +1,20 @@ -package com.server.dosopt.seminar.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -public class BCryptPasswordConfig { - - // salt 할 때 보안 강도를 어느정도로 할지 설정 - // 높을수록 세지는데, 어느정도 높아지면 비슷함 - // default가 10 - private static final int STRENGTH = 10; - - @Bean - public PasswordEncoder bCryptPasswordEncoder() { - return new BCryptPasswordEncoder(STRENGTH); - } -} +//package com.server.dosopt.seminar.config; +// +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +//import org.springframework.security.crypto.password.PasswordEncoder; +// +//@Configuration +//public class BCryptPasswordConfig { +// +// // salt 할 때 보안 강도를 어느정도로 할지 설정 +// // 높을수록 세지는데, 어느정도 높아지면 비슷함 +// // default가 10 +// private static final int STRENGTH = 10; +// +// @Bean +// public PasswordEncoder bCryptPasswordEncoder() { +// return new BCryptPasswordEncoder(STRENGTH); +// } +//} diff --git a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/JpaAuditingConfig.java b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/JpaAuditingConfig.java index 9a2cb6b..1039866 100644 --- a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/JpaAuditingConfig.java +++ b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/JpaAuditingConfig.java @@ -1,9 +1,9 @@ -package com.server.dosopt.seminar.config; - -import org.springframework.context.annotation.Configuration; -import org.springframework.data.jpa.repository.config.EnableJpaAuditing; - -@Configuration -@EnableJpaAuditing -public class JpaAuditingConfig { -} +//package com.server.dosopt.seminar.config; +// +//import org.springframework.context.annotation.Configuration; +//import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +// +//@Configuration +//@EnableJpaAuditing +//public class JpaAuditingConfig { +//} diff --git a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/SecurityConfig.java b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/SecurityConfig.java index e787886..e1c3a99 100644 --- a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/SecurityConfig.java +++ b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/SecurityConfig.java @@ -1,69 +1,69 @@ -package com.server.dosopt.seminar.config; - -import com.server.dosopt.seminar.config.jwt.CustomAccessDeniedHandler; -import com.server.dosopt.seminar.config.jwt.CustomJwtAuthenticationEntryPoint; -import com.server.dosopt.seminar.config.jwt.JwtAuthenticationFilter; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - - -@Configuration -@EnableWebSecurity -public class SecurityConfig { - - private final JwtAuthenticationFilter jwtAuthenticationFilter; - private final CustomJwtAuthenticationEntryPoint customJwtAuthenticationEntryPoint; - private final CustomAccessDeniedHandler customAccessDeniedHandler; - - private static final String[] AUTH_WHITELIST = { - "/sign-up", - "/sign-in" - }; - - public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter, CustomJwtAuthenticationEntryPoint customJwtAuthenticationEntryPoint, CustomAccessDeniedHandler customAccessDeniedHandler) { - this.jwtAuthenticationFilter = jwtAuthenticationFilter; - this.customJwtAuthenticationEntryPoint = customJwtAuthenticationEntryPoint; - this.customAccessDeniedHandler = customAccessDeniedHandler; - } - - - @Bean - SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { - return http - .csrf().disable() - .formLogin().disable() - .httpBasic().disable() -// .sessionManagement() -// .sessionCreationPolicy(STATELESS) +//package com.server.dosopt.seminar.config; +// +//import com.server.dosopt.seminar.config.jwt.CustomAccessDeniedHandler; +//import com.server.dosopt.seminar.config.jwt.CustomJwtAuthenticationEntryPoint; +//import com.server.dosopt.seminar.config.jwt.JwtAuthenticationFilter; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.security.config.annotation.web.builders.HttpSecurity; +//import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +//import org.springframework.security.web.SecurityFilterChain; +//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +//import org.springframework.web.servlet.config.annotation.CorsRegistry; +//import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +// +// +//@Configuration +//@EnableWebSecurity +//public class SecurityConfig { +// +// private final JwtAuthenticationFilter jwtAuthenticationFilter; +// private final CustomJwtAuthenticationEntryPoint customJwtAuthenticationEntryPoint; +// private final CustomAccessDeniedHandler customAccessDeniedHandler; +// +// private static final String[] AUTH_WHITELIST = { +// "/sign-up", +// "/sign-in" +// }; +// +// public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter, CustomJwtAuthenticationEntryPoint customJwtAuthenticationEntryPoint, CustomAccessDeniedHandler customAccessDeniedHandler) { +// this.jwtAuthenticationFilter = jwtAuthenticationFilter; +// this.customJwtAuthenticationEntryPoint = customJwtAuthenticationEntryPoint; +// this.customAccessDeniedHandler = customAccessDeniedHandler; +// } +// +// +// @Bean +// SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { +// return http +// .csrf().disable() +// .formLogin().disable() +// .httpBasic().disable() +//// .sessionManagement() +//// .sessionCreationPolicy(STATELESS) +//// .and() +// .exceptionHandling() +// .authenticationEntryPoint(customJwtAuthenticationEntryPoint) +// .accessDeniedHandler(customAccessDeniedHandler) // .and() - .exceptionHandling() - .authenticationEntryPoint(customJwtAuthenticationEntryPoint) - .accessDeniedHandler(customAccessDeniedHandler) - .and() - .authorizeHttpRequests() - .requestMatchers(AUTH_WHITELIST).permitAll() - .anyRequest().authenticated() - .and() - .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) - .build(); - } - - @Bean - public WebMvcConfigurer corsConfigurer() { - return new WebMvcConfigurer() { - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowedOrigins("*") - .allowedOriginPatterns("*") - .allowedMethods("*"); - } - }; - } -} +// .authorizeHttpRequests() +// .requestMatchers(AUTH_WHITELIST).permitAll() +// .anyRequest().authenticated() +// .and() +// .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class) +// .build(); +// } +// +// @Bean +// public WebMvcConfigurer corsConfigurer() { +// return new WebMvcConfigurer() { +// @Override +// public void addCorsMappings(CorsRegistry registry) { +// registry.addMapping("/**") +// .allowedOrigins("*") +// .allowedOriginPatterns("*") +// .allowedMethods("*"); +// } +// }; +// } +//} diff --git a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/CustomAccessDeniedHandler.java b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/CustomAccessDeniedHandler.java index 79c33d2..b3783a6 100644 --- a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/CustomAccessDeniedHandler.java +++ b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/CustomAccessDeniedHandler.java @@ -1,22 +1,22 @@ -package com.server.dosopt.seminar.config.jwt; - -import jakarta.servlet.ServletException; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.security.web.access.AccessDeniedHandler; -import org.springframework.stereotype.Component; - -import java.io.IOException; - -@Component -public class CustomAccessDeniedHandler implements AccessDeniedHandler { - @Override - public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { - setResponse(response); - } - - private void setResponse(HttpServletResponse response) { - response.setStatus(HttpServletResponse.SC_FORBIDDEN); - } -} \ No newline at end of file +//package com.server.dosopt.seminar.config.jwt; +// +//import jakarta.servlet.ServletException; +//import jakarta.servlet.http.HttpServletRequest; +//import jakarta.servlet.http.HttpServletResponse; +//import org.springframework.security.access.AccessDeniedException; +//import org.springframework.security.web.access.AccessDeniedHandler; +//import org.springframework.stereotype.Component; +// +//import java.io.IOException; +// +//@Component +//public class CustomAccessDeniedHandler implements AccessDeniedHandler { +// @Override +// public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException { +// setResponse(response); +// } +// +// private void setResponse(HttpServletResponse response) { +// response.setStatus(HttpServletResponse.SC_FORBIDDEN); +// } +//} \ No newline at end of file diff --git a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/CustomJwtAuthenticationEntryPoint.java b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/CustomJwtAuthenticationEntryPoint.java index c2a2e0e..6fa96f5 100644 --- a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/CustomJwtAuthenticationEntryPoint.java +++ b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/CustomJwtAuthenticationEntryPoint.java @@ -1,20 +1,20 @@ -package com.server.dosopt.seminar.config.jwt; - -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.stereotype.Component; - -@Component -public class CustomJwtAuthenticationEntryPoint implements AuthenticationEntryPoint { - - @Override - public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) { - setResponse(response); - } - - private void setResponse(HttpServletResponse response) { - response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } -} \ No newline at end of file +//package com.server.dosopt.seminar.config.jwt; +// +//import jakarta.servlet.http.HttpServletRequest; +//import jakarta.servlet.http.HttpServletResponse; +//import org.springframework.security.core.AuthenticationException; +//import org.springframework.security.web.AuthenticationEntryPoint; +//import org.springframework.stereotype.Component; +// +//@Component +//public class CustomJwtAuthenticationEntryPoint implements AuthenticationEntryPoint { +// +// @Override +// public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) { +// setResponse(response); +// } +// +// private void setResponse(HttpServletResponse response) { +// response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); +// } +//} \ No newline at end of file diff --git a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/JwtAuthenticationFilter.java b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/JwtAuthenticationFilter.java index cf7e6e2..8af0f1b 100644 --- a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/JwtAuthenticationFilter.java +++ b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/JwtAuthenticationFilter.java @@ -1,52 +1,52 @@ -package com.server.dosopt.seminar.config.jwt; - -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import lombok.NonNull; -import lombok.RequiredArgsConstructor; -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; - -import java.io.IOException; - -import static com.server.dosopt.seminar.domain.JwtValidationType.VALID_JWT; - -@Component -@RequiredArgsConstructor -public class JwtAuthenticationFilter extends OncePerRequestFilter { - - private final JwtTokenProvider jwtTokenProvider; - - @Override - protected void doFilterInternal(@NonNull HttpServletRequest request, - @NonNull HttpServletResponse response, - @NonNull FilterChain filterChain) throws ServletException, IOException { - try { - final String token = getJwtFromRequest(request); - if (jwtTokenProvider.validateToken(token) == VALID_JWT) { - Long memberId = jwtTokenProvider.getUserFromJwt(token); - // authentication 객체 생성 -> principal에 유저정보를 담는다. - UserAuthentication authentication = new UserAuthentication(memberId.toString(), null, null); - authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); - SecurityContextHolder.getContext().setAuthentication(authentication); - } - } catch (Exception exception) { - throw new RuntimeException(); - } - // 다음 필터로 요청 전달 - filterChain.doFilter(request, response); - } - - private String getJwtFromRequest(HttpServletRequest request) { - String bearerToken = request.getHeader("Authorization"); - if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { - return bearerToken.substring("Bearer ".length()); - } - return null; - } -} \ No newline at end of file +//package com.server.dosopt.seminar.config.jwt; +// +//import jakarta.servlet.FilterChain; +//import jakarta.servlet.ServletException; +//import jakarta.servlet.http.HttpServletRequest; +//import jakarta.servlet.http.HttpServletResponse; +//import lombok.NonNull; +//import lombok.RequiredArgsConstructor; +//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; +// +//import java.io.IOException; +// +//import static com.server.dosopt.seminar.domain.JwtValidationType.VALID_JWT; +// +//@Component +//@RequiredArgsConstructor +//public class JwtAuthenticationFilter extends OncePerRequestFilter { +// +// private final JwtTokenProvider jwtTokenProvider; +// +// @Override +// protected void doFilterInternal(@NonNull HttpServletRequest request, +// @NonNull HttpServletResponse response, +// @NonNull FilterChain filterChain) throws ServletException, IOException { +// try { +// final String token = getJwtFromRequest(request); +// if (jwtTokenProvider.validateToken(token) == VALID_JWT) { +// Long memberId = jwtTokenProvider.getUserFromJwt(token); +// // authentication 객체 생성 -> principal에 유저정보를 담는다. +// UserAuthentication authentication = new UserAuthentication(memberId.toString(), null, null); +// authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); +// SecurityContextHolder.getContext().setAuthentication(authentication); +// } +// } catch (Exception exception) { +// throw new RuntimeException(); +// } +// // 다음 필터로 요청 전달 +// filterChain.doFilter(request, response); +// } +// +// private String getJwtFromRequest(HttpServletRequest request) { +// String bearerToken = request.getHeader("Authorization"); +// if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { +// return bearerToken.substring("Bearer ".length()); +// } +// return null; +// } +//} \ No newline at end of file diff --git a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/JwtTokenProvider.java b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/JwtTokenProvider.java index 1704701..ef383b2 100644 --- a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/JwtTokenProvider.java +++ b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/JwtTokenProvider.java @@ -1,81 +1,81 @@ -package com.server.dosopt.seminar.config.jwt; - -import com.server.dosopt.seminar.domain.JwtValidationType; -import io.jsonwebtoken.*; -import io.jsonwebtoken.security.Keys; -import jakarta.annotation.PostConstruct; -import lombok.RequiredArgsConstructor; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.core.Authentication; -import org.springframework.stereotype.Component; - -import javax.crypto.SecretKey; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Date; - -@Component -@RequiredArgsConstructor -public class JwtTokenProvider { - - private static final String MEMBER_ID = "memberId"; - - @Value("${jwt.secret}") - private String JWT_SECRET; - - @PostConstruct - protected void init() { - //base64 라이브러리에서 encodeToString을 이용해서 byte[] 형식을 String 형식으로 변환 - JWT_SECRET = Base64.getEncoder().encodeToString(JWT_SECRET.getBytes(StandardCharsets.UTF_8)); - } - - public String generateToken(Authentication authentication, Long tokenExpirationTime) { - final Date now = new Date(); - - final Claims claims = Jwts.claims() - .setIssuedAt(now) - .setExpiration(new Date(now.getTime() + tokenExpirationTime)); // 만료 시간 - - claims.put(MEMBER_ID, authentication.getPrincipal()); - - return Jwts.builder() - .setHeaderParam(Header.TYPE, Header.JWT_TYPE) // Header - .setClaims(claims) // Claim - .signWith(getSigningKey()) // Signature - .compact(); - } - - private SecretKey getSigningKey() { - String encodedKey = Base64.getEncoder().encodeToString(JWT_SECRET.getBytes()); //SecretKey 통해 서명 생성 - return Keys.hmacShaKeyFor(encodedKey.getBytes()); //일반적으로 HMAC (Hash-based Message Authentication Code) 알고리즘 사용 - } - - public JwtValidationType validateToken(String token) { - try { - final Claims claims = getBody(token); - return JwtValidationType.VALID_JWT; - } catch (MalformedJwtException ex) { - return JwtValidationType.INVALID_JWT_TOKEN; - } catch (ExpiredJwtException ex) { - return JwtValidationType.EXPIRED_JWT_TOKEN; - } catch (UnsupportedJwtException ex) { - return JwtValidationType.UNSUPPORTED_JWT_TOKEN; - } catch (IllegalArgumentException ex) { - return JwtValidationType.EMPTY_JWT; - } - } - - private Claims getBody(final String token) { - return Jwts.parserBuilder() - .setSigningKey(getSigningKey()) - .build() - .parseClaimsJws(token) - .getBody(); - } - - public Long getUserFromJwt(String token) { - Claims claims = getBody(token); - return Long.valueOf(claims.get(MEMBER_ID).toString()); - } - -} \ No newline at end of file +//package com.server.dosopt.seminar.config.jwt; +// +//import com.server.dosopt.seminar.domain.JwtValidationType; +//import io.jsonwebtoken.*; +//import io.jsonwebtoken.security.Keys; +//import jakarta.annotation.PostConstruct; +//import lombok.RequiredArgsConstructor; +//import org.springframework.beans.factory.annotation.Value; +//import org.springframework.security.core.Authentication; +//import org.springframework.stereotype.Component; +// +//import javax.crypto.SecretKey; +//import java.nio.charset.StandardCharsets; +//import java.util.Base64; +//import java.util.Date; +// +//@Component +//@RequiredArgsConstructor +//public class JwtTokenProvider { +// +// private static final String MEMBER_ID = "memberId"; +// +// @Value("${jwt.secret}") +// private String JWT_SECRET; +// +// @PostConstruct +// protected void init() { +// //base64 라이브러리에서 encodeToString을 이용해서 byte[] 형식을 String 형식으로 변환 +// JWT_SECRET = Base64.getEncoder().encodeToString(JWT_SECRET.getBytes(StandardCharsets.UTF_8)); +// } +// +// public String generateToken(Authentication authentication, Long tokenExpirationTime) { +// final Date now = new Date(); +// +// final Claims claims = Jwts.claims() +// .setIssuedAt(now) +// .setExpiration(new Date(now.getTime() + tokenExpirationTime)); // 만료 시간 +// +// claims.put(MEMBER_ID, authentication.getPrincipal()); +// +// return Jwts.builder() +// .setHeaderParam(Header.TYPE, Header.JWT_TYPE) // Header +// .setClaims(claims) // Claim +// .signWith(getSigningKey()) // Signature +// .compact(); +// } +// +// private SecretKey getSigningKey() { +// String encodedKey = Base64.getEncoder().encodeToString(JWT_SECRET.getBytes()); //SecretKey 통해 서명 생성 +// return Keys.hmacShaKeyFor(encodedKey.getBytes()); //일반적으로 HMAC (Hash-based Message Authentication Code) 알고리즘 사용 +// } +// +// public JwtValidationType validateToken(String token) { +// try { +// final Claims claims = getBody(token); +// return JwtValidationType.VALID_JWT; +// } catch (MalformedJwtException ex) { +// return JwtValidationType.INVALID_JWT_TOKEN; +// } catch (ExpiredJwtException ex) { +// return JwtValidationType.EXPIRED_JWT_TOKEN; +// } catch (UnsupportedJwtException ex) { +// return JwtValidationType.UNSUPPORTED_JWT_TOKEN; +// } catch (IllegalArgumentException ex) { +// return JwtValidationType.EMPTY_JWT; +// } +// } +// +// private Claims getBody(final String token) { +// return Jwts.parserBuilder() +// .setSigningKey(getSigningKey()) +// .build() +// .parseClaimsJws(token) +// .getBody(); +// } +// +// public Long getUserFromJwt(String token) { +// Claims claims = getBody(token); +// return Long.valueOf(claims.get(MEMBER_ID).toString()); +// } +// +//} \ No newline at end of file diff --git a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/UserAuthentication.java b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/UserAuthentication.java index 64159d7..db40d47 100644 --- a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/UserAuthentication.java +++ b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/config/jwt/UserAuthentication.java @@ -1,14 +1,14 @@ -package com.server.dosopt.seminar.config.jwt; - -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.GrantedAuthority; - -import java.util.Collection; - -public class UserAuthentication extends UsernamePasswordAuthenticationToken { - - // 사용자 인증 객체 생성 - public UserAuthentication(Object principal, Object credentials, Collection authorities) { - super(principal, credentials, authorities); - } -} \ No newline at end of file +//package com.server.dosopt.seminar.config.jwt; +// +//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +//import org.springframework.security.core.GrantedAuthority; +// +//import java.util.Collection; +// +//public class UserAuthentication extends UsernamePasswordAuthenticationToken { +// +// // 사용자 인증 객체 생성 +// public UserAuthentication(Object principal, Object credentials, Collection authorities) { +// super(principal, credentials, authorities); +// } +//} \ No newline at end of file diff --git a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/controller/ServiceMemberController.java b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/controller/ServiceMemberController.java index d44ee57..528cf8a 100644 --- a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/controller/ServiceMemberController.java +++ b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/controller/ServiceMemberController.java @@ -1,32 +1,32 @@ -package com.server.dosopt.seminar.controller; - -import com.server.dosopt.seminar.dto.request.servicemember.ServiceMemberRequest; -import com.server.dosopt.seminar.service.ServiceMemberService; -import lombok.RequiredArgsConstructor; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.net.URI; - -@RestController -@RequiredArgsConstructor -@RequestMapping("/api/users/") -public class ServiceMemberController { - - private final ServiceMemberService serviceMemberService; - - @PostMapping("sign-up") - public ResponseEntity signUp(@RequestBody ServiceMemberRequest request) { - URI location = URI.create(serviceMemberService.create(request)); - return ResponseEntity.created(location).build(); - } - - @PostMapping("sign-in") - public ResponseEntity signIn(@RequestBody ServiceMemberRequest request) { - serviceMemberService.signIn(request); - return ResponseEntity.noContent().build(); - } -} +//package com.server.dosopt.seminar.controller; +// +//import com.server.dosopt.seminar.dto.request.servicemember.ServiceMemberRequest; +//import com.server.dosopt.seminar.service.ServiceMemberService; +//import lombok.RequiredArgsConstructor; +//import org.springframework.http.ResponseEntity; +//import org.springframework.web.bind.annotation.PostMapping; +//import org.springframework.web.bind.annotation.RequestBody; +//import org.springframework.web.bind.annotation.RequestMapping; +//import org.springframework.web.bind.annotation.RestController; +// +//import java.net.URI; +// +//@RestController +//@RequiredArgsConstructor +//@RequestMapping("/api/users/") +//public class ServiceMemberController { +// +// private final ServiceMemberService serviceMemberService; +// +// @PostMapping("sign-up") +// public ResponseEntity signUp(@RequestBody ServiceMemberRequest request) { +// URI location = URI.create(serviceMemberService.create(request)); +// return ResponseEntity.created(location).build(); +// } +// +// @PostMapping("sign-in") +// public ResponseEntity signIn(@RequestBody ServiceMemberRequest request) { +// serviceMemberService.signIn(request); +// return ResponseEntity.noContent().build(); +// } +//} diff --git a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/service/ServiceMemberService.java b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/service/ServiceMemberService.java index 935dad9..146d7a2 100644 --- a/ThirdSeminar/src/main/java/com/server/dosopt/seminar/service/ServiceMemberService.java +++ b/ThirdSeminar/src/main/java/com/server/dosopt/seminar/service/ServiceMemberService.java @@ -1,39 +1,39 @@ -package com.server.dosopt.seminar.service; - -import com.server.dosopt.seminar.domain.ServiceMember; -import com.server.dosopt.seminar.dto.request.servicemember.ServiceMemberRequest; -import com.server.dosopt.seminar.repository.ServiceMemberJpaRepository; -import lombok.RequiredArgsConstructor; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -@Service -@RequiredArgsConstructor -@Transactional(readOnly = true) -public class ServiceMemberService { - - private final ServiceMemberJpaRepository serviceMemberJpaRepository; - private final PasswordEncoder passwordEncoder; - - @Transactional - public String create(ServiceMemberRequest request) { - ServiceMember serviceMember = ServiceMember.builder() - .nickname(request.nickname()) - .password(passwordEncoder.encode(request.password())) - .build(); - serviceMemberJpaRepository.save(serviceMember); - - return serviceMember.getId().toString(); - } - - public void signIn(ServiceMemberRequest request) { - ServiceMember serviceMember = serviceMemberJpaRepository.findByNickname(request.nickname()); - if (serviceMember == null) { - throw new RuntimeException("해당하는 회원이 없습니다."); - } - if (!passwordEncoder.matches(request.password(), serviceMember.getPassword())) { - throw new RuntimeException("비밀번호가 일치하지 않습니다."); - } - } -} \ No newline at end of file +//package com.server.dosopt.seminar.service; +// +//import com.server.dosopt.seminar.domain.ServiceMember; +//import com.server.dosopt.seminar.dto.request.servicemember.ServiceMemberRequest; +//import com.server.dosopt.seminar.repository.ServiceMemberJpaRepository; +//import lombok.RequiredArgsConstructor; +//import org.springframework.security.crypto.password.PasswordEncoder; +//import org.springframework.stereotype.Service; +//import org.springframework.transaction.annotation.Transactional; +// +//@Service +//@RequiredArgsConstructor +//@Transactional(readOnly = true) +//public class ServiceMemberService { +// +// private final ServiceMemberJpaRepository serviceMemberJpaRepository; +// private final PasswordEncoder passwordEncoder; +// +// @Transactional +// public String create(ServiceMemberRequest request) { +// ServiceMember serviceMember = ServiceMember.builder() +// .nickname(request.nickname()) +// .password(passwordEncoder.encode(request.password())) +// .build(); +// serviceMemberJpaRepository.save(serviceMember); +// +// return serviceMember.getId().toString(); +// } +// +// public void signIn(ServiceMemberRequest request) { +// ServiceMember serviceMember = serviceMemberJpaRepository.findByNickname(request.nickname()); +// if (serviceMember == null) { +// throw new RuntimeException("해당하는 회원이 없습니다."); +// } +// if (!passwordEncoder.matches(request.password(), serviceMember.getPassword())) { +// throw new RuntimeException("비밀번호가 일치하지 않습니다."); +// } +// } +//} \ No newline at end of file diff --git a/ThirdSeminar/src/main/resources/data.sql b/ThirdSeminar/src/main/resources/data.sql index 300eb00..b741158 100644 --- a/ThirdSeminar/src/main/resources/data.sql +++ b/ThirdSeminar/src/main/resources/data.sql @@ -1,20 +1,18 @@ -INSERT INTO MEMBER(ID, NICKNAME, NAME, AGE, PART, GENERATION) +INSERT INTO member(ID, NICKNAME, NAME, AGE, PART, GENERATION) VALUES (1, '유난', '최윤한', 20, 'SERVER', 33), (2, 'DDD', '정준서', 24, 'SERVER', 33), (3, '멜로니', '김해린', 26, 'PLAN', 33), (4, '티벳여우', '이태희', 25, 'ANDROID', 33); -INSERT INTO POST(ID, TITLE, CONTENT, MEMBER_ID, CATEGORY_ID) -VALUES - (1, '안녕하세요 제목1', '안녕하세요 내용1', 1, 1), - (2, '안녕하세요 제목2', '안녕하세요 내용2', 1, 2), - (3, '안녕하세요 제목3', '안녕하세요 내용3', 1, 3), - (4, '반갑습니다 제목4', '반갑습니다', 2, 3), - (5, '안녕하세요 제목5', '안녕하세요', 3, 3); +INSERT INTO post(ID, TITLE, CONTENT, MEMBER_ID, CATEGORY_ID) +VALUES (1, '안녕하세요 제목1', '안녕하세요 내용1', 1, 1), + (2, '안녕하세요 제목2', '안녕하세요 내용2', 1, 2), + (3, '안녕하세요 제목3', '안녕하세요 내용3', 1, 3), + (4, '반갑습니다 제목4', '반갑습니다', 2, 3), + (5, '안녕하세요 제목5', '안녕하세요', 3, 3); -INSERT INTO CATEGORY(ID, CONTENT) -VALUES - (1, '일상'), - (2, '여행'), - (3, '공부'); \ No newline at end of file +INSERT INTO category(ID, CONTENT) +VALUES (1, '일상'), + (2, '여행'), + (3, '공부'); \ No newline at end of file