From 86da0d461a0965306bd5b2153d70b6c6d6b15707 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=9D=B4=EC=84=B1=ED=98=B8?= <33485494+dltjdgh0428@users.noreply.github.com> Date: Fri, 29 Mar 2024 00:25:13 +0900 Subject: [PATCH 01/51] Update CICD.yml --- .github/workflows/CICD.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/CICD.yml b/.github/workflows/CICD.yml index 5cae0da..46ecba3 100644 --- a/.github/workflows/CICD.yml +++ b/.github/workflows/CICD.yml @@ -52,7 +52,7 @@ jobs: if [ "$STATUS" = "200" ]; then CURRENT_UPSTREAM=$(curl -s "https://${{ secrets.BOOKEVERYWHERE_URL }}/env" | jq -r '.data') else - CURRENT_UPSTREAM=blue + CURRENT_UPSTREAM=green fi echo CURRENT_UPSTREAM=$CURRENT_UPSTREAM >> $GITHUB_ENV if [ $CURRENT_UPSTREAM = blue ]; then From dffe2f3467cf5d40cbb5dcc448d7e0ab4d0ff4a5 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Fri, 29 Mar 2024 02:18:55 +0900 Subject: [PATCH 02/51] =?UTF-8?q?feat=20:=20JWT=20=ED=95=84=ED=84=B0?= =?UTF-8?q?=EA=B9=8C=EC=A7=80=20=EB=A7=8C=EB=93=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 5 ++ .../auth/config/SecurityConfig.java | 22 +++--- .../auth/dto/CustomOAuth2User.java | 8 +- .../book_everywhere/auth/jwt/JWTFilter.java | 75 +++++++++++++++++++ .../com/book_everywhere/auth/jwt/JWTUtil.java | 44 +++++++++++ .../auth/service/CustomOAuth2UserService.java | 10 +-- .../service/CustomUserDetailsService.java | 33 -------- .../oauth2/CustomSuccessHandler.java | 54 +++++++++++++ 8 files changed, 195 insertions(+), 56 deletions(-) create mode 100644 src/main/java/com/book_everywhere/auth/jwt/JWTFilter.java create mode 100644 src/main/java/com/book_everywhere/auth/jwt/JWTUtil.java delete mode 100644 src/main/java/com/book_everywhere/auth/service/CustomUserDetailsService.java create mode 100644 src/main/java/com/book_everywhere/oauth2/CustomSuccessHandler.java diff --git a/build.gradle b/build.gradle index 42b1ebf..8bfa4f1 100644 --- a/build.gradle +++ b/build.gradle @@ -34,6 +34,11 @@ dependencies { testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test' + //JWT + implementation 'io.jsonwebtoken:jjwt-api:0.12.3' + implementation 'io.jsonwebtoken:jjwt-impl:0.12.3' + implementation 'io.jsonwebtoken:jjwt-jackson:0.12.3' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' //log를 위한 추가 diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 29f37ff..6d110a8 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -1,6 +1,10 @@ package com.book_everywhere.auth.config; +import com.book_everywhere.auth.jwt.JWTFilter; +import com.book_everywhere.auth.jwt.JWTUtil; import com.book_everywhere.auth.service.CustomOAuth2UserService; +import com.book_everywhere.oauth2.CustomSuccessHandler; +import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @@ -8,7 +12,9 @@ import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.servlet.handler.HandlerMappingIntrospector; @@ -19,13 +25,13 @@ @Configuration @EnableWebSecurity +@RequiredArgsConstructor public class SecurityConfig { private final CustomOAuth2UserService customOAuth2UserService; + private final CustomSuccessHandler customSuccessHandler; + private final JWTUtil jwtUtil; - public SecurityConfig(CustomOAuth2UserService customOAuth2UserService) { - this.customOAuth2UserService = customOAuth2UserService; - } @Bean public BCryptPasswordEncoder encoder() { @@ -37,7 +43,6 @@ public BCryptPasswordEncoder encoder() { public CorsConfigurationSource corsConfigurationSource() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); - // 또는 패턴을 사용하여 출처 지정 config.setAllowedOriginPatterns(Arrays.asList("https://*.bookeverywhere.site","http://localhost:3000")); config.setAllowCredentials(true); // 크리덴셜 허용 config.addAllowedHeader("*"); @@ -51,12 +56,13 @@ public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospe http .sessionManagement(sessionManagement -> - sessionManagement.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) + sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS) ) .cors(cors -> cors.configurationSource(corsConfigurationSource())) .csrf(AbstractHttpConfigurer::disable) .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) + .addFilterBefore(new JWTFilter(jwtUtil), OAuth2LoginAuthenticationFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers(new MvcRequestMatcher(introspector, "/")).permitAll() .requestMatchers(new MvcRequestMatcher(introspector, "/health")).permitAll() @@ -67,16 +73,14 @@ public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospe .requestMatchers(new MvcRequestMatcher(introspector, "/api/map")).permitAll() .requestMatchers(new MvcRequestMatcher(introspector, "/api/tags")).permitAll() .requestMatchers(new MvcRequestMatcher(introspector, "/api/data/**")).permitAll() - .requestMatchers(new MvcRequestMatcher(introspector, "/api/**")).hasRole("MEMBER") + .requestMatchers(new MvcRequestMatcher(introspector, "/api/**")).hasAuthority("ROLE_MEMBER") .anyRequest().authenticated() ) .oauth2Login(oauth2Login -> oauth2Login .userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig.userService(customOAuth2UserService)) - .successHandler((request, response, authentication) -> { - response.sendRedirect("https://www.bookeverywhere.site"); - })) + .successHandler(customSuccessHandler)) ; return http.build(); } diff --git a/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java b/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java index ace35c2..c879baa 100644 --- a/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java +++ b/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java @@ -1,6 +1,7 @@ package com.book_everywhere.auth.dto; import com.book_everywhere.auth.entity.Role; +import lombok.RequiredArgsConstructor; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.user.OAuth2User; @@ -8,17 +9,12 @@ import java.util.Collection; import java.util.Map; +@RequiredArgsConstructor public class CustomOAuth2User implements OAuth2User { private final OAuthAttributes oAuthAttributes; private final Role role; - public CustomOAuth2User(OAuthAttributes oAuth2Attributes, Role role) { - - this.oAuthAttributes = oAuth2Attributes; - this.role = role; - } - @Override public Map getAttributes() { return oAuthAttributes.getAttributes(); diff --git a/src/main/java/com/book_everywhere/auth/jwt/JWTFilter.java b/src/main/java/com/book_everywhere/auth/jwt/JWTFilter.java new file mode 100644 index 0000000..005f4f3 --- /dev/null +++ b/src/main/java/com/book_everywhere/auth/jwt/JWTFilter.java @@ -0,0 +1,75 @@ +package com.book_everywhere.auth.jwt; + +import com.book_everywhere.auth.dto.CustomOAuth2User; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import java.io.IOException; + +@RequiredArgsConstructor +public class JWTFilter extends OncePerRequestFilter { + + private final JWTUtil jwtUtil; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + + //cookie들을 불러온 뒤 Authorization Key에 담긴 쿠키를 찾음 + String authorization = null; + Cookie[] cookies = request.getCookies(); + for (Cookie cookie : cookies) { + + System.out.println(cookie.getName()); + if (cookie.getName().equals("Authorization")) { + + authorization = cookie.getValue(); + } + } + + //Authorization 헤더 검증 + if (authorization == null) { + + System.out.println("token null"); + filterChain.doFilter(request, response); + + //조건이 해당되면 메소드 종료 (필수) + return; + } + + //토큰 + String token = authorization; + + //토큰 소멸 시간 검증 + if (jwtUtil.isExpired(token)) { + + System.out.println("token expired"); + filterChain.doFilter(request, response); + + //조건이 해당되면 메소드 종료 (필수) + return; + } + + //토큰에서 username과 role 획득 + String username = jwtUtil.getUsername(token); + String role = jwtUtil.getRole(token); + + + //UserDetails에 회원 정보 객체 담기 + CustomOAuth2User customOAuth2User = new CustomOAuth2User(username, role); + + //스프링 시큐리티 인증 토큰 생성 + Authentication authToken = new UsernamePasswordAuthenticationToken(customOAuth2User, null, customOAuth2User.getAuthorities()); + //세션에 사용자 등록 + SecurityContextHolder.getContext().setAuthentication(authToken); + + filterChain.doFilter(request, response); + } +} \ No newline at end of file diff --git a/src/main/java/com/book_everywhere/auth/jwt/JWTUtil.java b/src/main/java/com/book_everywhere/auth/jwt/JWTUtil.java new file mode 100644 index 0000000..51495ed --- /dev/null +++ b/src/main/java/com/book_everywhere/auth/jwt/JWTUtil.java @@ -0,0 +1,44 @@ +package com.book_everywhere.auth.jwt; + + +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.util.Date; + +import io.jsonwebtoken.Jwts; +import org.springframework.beans.factory.annotation.Value; + +@Component +public class JWTUtil { + + private SecretKey secretKey; + + public JWTUtil(@Value("${app.jwt.secret}") String secret) { + secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), Jwts.SIG.HS256.key().build().getAlgorithm()); + } + + public String getUsername(String token) { + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("username", String.class); + } + + public String getRole(String token) { + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); + } + + public Boolean isExpired(String token) { + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date()); + } + + public String createJwt(String username, String role, Long expiredMs) { + return Jwts.builder() + .claim("username", username) + .claim("role", role) + .issuedAt(new Date(System.currentTimeMillis())) + .expiration(new Date(System.currentTimeMillis() + expiredMs)) + .signWith(secretKey) + .compact(); + } +} \ No newline at end of file diff --git a/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java b/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java index 3f99818..57fd084 100644 --- a/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java +++ b/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java @@ -26,11 +26,10 @@ @RequiredArgsConstructor @Service @Slf4j -public class CustomOAuth2UserService implements OAuth2UserService { +public class CustomOAuth2UserService extends DefaultOAuth2UserService { private final UserRepository userRepository; private final HttpSession httpSession; - private final CustomUserDetailsService customUserDetailsService; /** * loadUser 메서드에서는 DefaultOAuth2UserService를 사용하여 OAuth2UserRequest에 대한 OAuth2User 객체를 로드합니다. @@ -39,8 +38,7 @@ public class CustomOAuth2UserService implements OAuth2UserService delegate = new DefaultOAuth2UserService(); - OAuth2User oAuth2User = delegate.loadUser(userRequest); + OAuth2User oAuth2User = super.loadUser(userRequest); String registrationId = userRequest.getClientRegistration().getRegistrationId(); String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName(); @@ -51,10 +49,6 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic httpSession.setAttribute("user", user); - UserDetails userDetails = customUserDetailsService.loadUserBySocialId(user.getSocialId()); - Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); - SecurityContextHolder.getContext().setAuthentication(authentication); - return new CustomOAuth2User(attributes,user.getRole()); } diff --git a/src/main/java/com/book_everywhere/auth/service/CustomUserDetailsService.java b/src/main/java/com/book_everywhere/auth/service/CustomUserDetailsService.java deleted file mode 100644 index 9c8f9f1..0000000 --- a/src/main/java/com/book_everywhere/auth/service/CustomUserDetailsService.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.book_everywhere.auth.service; - -import com.book_everywhere.auth.entity.User; -import com.book_everywhere.auth.repository.UserRepository; -import lombok.RequiredArgsConstructor; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Service; - -import java.util.Collections; -@Service -@RequiredArgsConstructor -public class CustomUserDetailsService implements UserDetailsService { - - private final UserRepository userRepository; - - public UserDetails loadUserBySocialId(Long socialId) { - User user = userRepository.findBySocialId(socialId) - .orElseThrow(() -> new UsernameNotFoundException("User not found with social ID: " + socialId)); - - return new org.springframework.security.core.userdetails.User( - user.getNickname(), - "", // 소셜 로그인이므로 비밀번호는 사용하지 않음 - Collections.singletonList(new SimpleGrantedAuthority(user.getRole().name()))); // 권한 설정 - } - - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - throw new UnsupportedOperationException("loadUserByUsername is not supported"); - } -} diff --git a/src/main/java/com/book_everywhere/oauth2/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/oauth2/CustomSuccessHandler.java new file mode 100644 index 0000000..629d4ae --- /dev/null +++ b/src/main/java/com/book_everywhere/oauth2/CustomSuccessHandler.java @@ -0,0 +1,54 @@ +package com.book_everywhere.oauth2; + +import com.book_everywhere.auth.dto.CustomOAuth2User; +import com.book_everywhere.auth.jwt.JWTUtil; +import jakarta.servlet.ServletException; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.util.Collection; +import java.util.Iterator; + +@RequiredArgsConstructor +@Component +public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { + + private final JWTUtil jwtUtil; + + @Override + public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { + + //OAuth2User + CustomOAuth2User customUserDetails = (CustomOAuth2User) authentication.getPrincipal(); + + String username = customUserDetails.getName(); + + Collection authorities = authentication.getAuthorities(); + Iterator iterator = authorities.iterator(); + GrantedAuthority auth = iterator.next(); + String role = auth.getAuthority(); + + String token = jwtUtil.createJwt(username, role, 60*60*60L); + + response.addCookie(createCookie("Authorization", token)); + response.sendRedirect("http://localhost:3000/"); + } + + private Cookie createCookie(String key, String value) { + + Cookie cookie = new Cookie(key, value); + cookie.setMaxAge(60*60*60); + //cookie.setSecure(true); + cookie.setPath("/"); + cookie.setHttpOnly(true); + + return cookie; + } +} From 00b03bce9ef578c5a7ea2f6f043704ff3943c316 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Sun, 31 Mar 2024 21:58:01 +0900 Subject: [PATCH 03/51] =?UTF-8?q?feat=20:=20JWT=20=EA=B8=B0=EB=B0=98=20?= =?UTF-8?q?=EC=84=B8=EC=85=98=20=EC=9D=B8=EC=A6=9D=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/config/SecurityConfig.java | 24 ++++++++++--------- .../auth/dto/CustomOAuth2User.java | 16 ++++++------- .../com/book_everywhere/auth/dto/UserDto.java | 10 ++++++++ .../book_everywhere/auth/jwt/JWTFilter.java | 8 ++++--- .../com/book_everywhere/auth/jwt/JWTUtil.java | 5 ++-- .../auth/service/CustomOAuth2UserService.java | 6 ++++- src/main/resources/templates/admin.html | 10 ++++++++ src/main/resources/templates/login.html | 12 ++++++++++ 8 files changed, 66 insertions(+), 25 deletions(-) create mode 100644 src/main/java/com/book_everywhere/auth/dto/UserDto.java create mode 100644 src/main/resources/templates/admin.html create mode 100644 src/main/resources/templates/login.html diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 6d110a8..c6205b5 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -52,7 +52,7 @@ public CorsConfigurationSource corsConfigurationSource() { } @Bean - public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception { + public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .sessionManagement(sessionManagement -> @@ -64,16 +64,18 @@ public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospe .httpBasic(AbstractHttpConfigurer::disable) .addFilterBefore(new JWTFilter(jwtUtil), OAuth2LoginAuthenticationFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests - .requestMatchers(new MvcRequestMatcher(introspector, "/")).permitAll() - .requestMatchers(new MvcRequestMatcher(introspector, "/health")).permitAll() - .requestMatchers(new MvcRequestMatcher(introspector, "/env")).permitAll() - .requestMatchers(new MvcRequestMatcher(introspector, "/test/**")).permitAll() - .requestMatchers(new MvcRequestMatcher(introspector, "/swagger-ui/**")).permitAll() - .requestMatchers(new MvcRequestMatcher(introspector, "/api/review")).permitAll() - .requestMatchers(new MvcRequestMatcher(introspector, "/api/map")).permitAll() - .requestMatchers(new MvcRequestMatcher(introspector, "/api/tags")).permitAll() - .requestMatchers(new MvcRequestMatcher(introspector, "/api/data/**")).permitAll() - .requestMatchers(new MvcRequestMatcher(introspector, "/api/**")).hasAuthority("ROLE_MEMBER") + .requestMatchers("/").permitAll() + .requestMatchers( "/login").permitAll() + .requestMatchers( "/health").permitAll() + .requestMatchers( "/env").permitAll() + .requestMatchers( "/test/**").permitAll() + .requestMatchers( "/swagger-ui/**").permitAll() + .requestMatchers("/api/review").permitAll() + .requestMatchers("/api/map").permitAll() + .requestMatchers("/api/tags").permitAll() + .requestMatchers( "/api/data/**").permitAll() + .requestMatchers( "/api/**").hasAuthority("ROLE_MEMBER") + .requestMatchers( "/admin").hasAuthority("ROLE_MEMBER") .anyRequest().authenticated() ) .oauth2Login(oauth2Login -> diff --git a/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java b/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java index c879baa..1e7c5c8 100644 --- a/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java +++ b/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java @@ -1,7 +1,5 @@ package com.book_everywhere.auth.dto; -import com.book_everywhere.auth.entity.Role; -import lombok.RequiredArgsConstructor; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.user.OAuth2User; @@ -9,15 +7,17 @@ import java.util.Collection; import java.util.Map; -@RequiredArgsConstructor public class CustomOAuth2User implements OAuth2User { - private final OAuthAttributes oAuthAttributes; - private final Role role; + private final UserDto userDto; + + public CustomOAuth2User(UserDto userDto) { + this.userDto = userDto; + } @Override public Map getAttributes() { - return oAuthAttributes.getAttributes(); + return null; } @Override @@ -28,7 +28,7 @@ public Collection getAuthorities() { collection.add(new GrantedAuthority() { @Override public String getAuthority() { - return String.valueOf(role); + return String.valueOf(userDto.getRole()); } }); @@ -38,7 +38,7 @@ public String getAuthority() { @Override public String getName() { - return oAuthAttributes.getNickname(); + return userDto.getNickname(); } diff --git a/src/main/java/com/book_everywhere/auth/dto/UserDto.java b/src/main/java/com/book_everywhere/auth/dto/UserDto.java new file mode 100644 index 0000000..8fab3cf --- /dev/null +++ b/src/main/java/com/book_everywhere/auth/dto/UserDto.java @@ -0,0 +1,10 @@ +package com.book_everywhere.auth.dto; + +import com.book_everywhere.auth.entity.Role; +import lombok.Data; + +@Data +public class UserDto { + private String nickname; + private Role role; +} diff --git a/src/main/java/com/book_everywhere/auth/jwt/JWTFilter.java b/src/main/java/com/book_everywhere/auth/jwt/JWTFilter.java index 005f4f3..a9ca7d0 100644 --- a/src/main/java/com/book_everywhere/auth/jwt/JWTFilter.java +++ b/src/main/java/com/book_everywhere/auth/jwt/JWTFilter.java @@ -1,6 +1,7 @@ package com.book_everywhere.auth.jwt; import com.book_everywhere.auth.dto.CustomOAuth2User; +import com.book_everywhere.auth.dto.UserDto; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; @@ -58,12 +59,13 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse } //토큰에서 username과 role 획득 - String username = jwtUtil.getUsername(token); - String role = jwtUtil.getRole(token); + UserDto userDto = new UserDto(); + userDto.setNickname(jwtUtil.getUsername(token)); + userDto.setRole(jwtUtil.getRole(token)); //UserDetails에 회원 정보 객체 담기 - CustomOAuth2User customOAuth2User = new CustomOAuth2User(username, role); + CustomOAuth2User customOAuth2User = new CustomOAuth2User(userDto); //스프링 시큐리티 인증 토큰 생성 Authentication authToken = new UsernamePasswordAuthenticationToken(customOAuth2User, null, customOAuth2User.getAuthorities()); diff --git a/src/main/java/com/book_everywhere/auth/jwt/JWTUtil.java b/src/main/java/com/book_everywhere/auth/jwt/JWTUtil.java index 51495ed..f66b25a 100644 --- a/src/main/java/com/book_everywhere/auth/jwt/JWTUtil.java +++ b/src/main/java/com/book_everywhere/auth/jwt/JWTUtil.java @@ -1,6 +1,7 @@ package com.book_everywhere.auth.jwt; +import com.book_everywhere.auth.entity.Role; import org.springframework.stereotype.Component; import javax.crypto.SecretKey; @@ -24,8 +25,8 @@ public String getUsername(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("username", String.class); } - public String getRole(String token) { - return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); + public Role getRole(String token) { + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", Role.class); } public Boolean isExpired(String token) { diff --git a/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java b/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java index 57fd084..0b7b407 100644 --- a/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java +++ b/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java @@ -2,6 +2,7 @@ import com.book_everywhere.auth.dto.CustomOAuth2User; import com.book_everywhere.auth.dto.OAuthAttributes; +import com.book_everywhere.auth.dto.UserDto; import com.book_everywhere.auth.entity.Role; import com.book_everywhere.auth.entity.User; import com.book_everywhere.auth.repository.UserRepository; @@ -47,9 +48,12 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic User user = saveOrUpdate(attributes); httpSession.setAttribute("user", user); + UserDto userDto = new UserDto(); + userDto.setNickname(user.getNickname()); + userDto.setRole(userDto.getRole()); - return new CustomOAuth2User(attributes,user.getRole()); + return new CustomOAuth2User(userDto); } /** diff --git a/src/main/resources/templates/admin.html b/src/main/resources/templates/admin.html new file mode 100644 index 0000000..75ea237 --- /dev/null +++ b/src/main/resources/templates/admin.html @@ -0,0 +1,10 @@ + + + + + Title + + +완료 + + \ No newline at end of file diff --git a/src/main/resources/templates/login.html b/src/main/resources/templates/login.html new file mode 100644 index 0000000..868e14a --- /dev/null +++ b/src/main/resources/templates/login.html @@ -0,0 +1,12 @@ + + + + + Title + + + + 카카오톡으로 간편 로그인 + + + \ No newline at end of file From 5f1940fd8a7a5ba3cdbf90947a7caeabb9b6ef1c Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 03:08:21 +0900 Subject: [PATCH 04/51] =?UTF-8?q?feat=20:=20JWT=20Refresh=20=ED=86=A0?= =?UTF-8?q?=ED=81=B0=20=EC=83=9D=EC=84=B1/=EC=82=AD=EC=A0=9C/=EC=9E=AC?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/config/SecurityConfig.java | 38 ++++---- .../com/book_everywhere/auth/jwt/JWTUtil.java | 45 ---------- .../jwt/controller/RefreshController.java | 82 ++++++++++++++++++ .../book_everywhere/jwt/domain/Refresh.java | 27 ++++++ .../book_everywhere/jwt/dto/RefreshDto.java | 33 +++++++ .../jwt/filter/CustomLogoutFilter.java | 77 +++++++++++++++++ .../filter}/CustomSuccessHandler.java | 35 ++++---- .../filter/JwtFilter.java} | 14 +-- .../jwt/repository/RefreshRepository.java | 15 ++++ .../jwt/service/RefreshService.java | 11 +++ .../jwt/service/RefreshServiceImpl.java | 40 +++++++++ .../jwt/token/JwtProvider.java | 86 +++++++++++++++++++ .../book_everywhere/jwt/token/TokenType.java | 18 ++++ .../domain/jwt/service/RefreshSeriveTest.java | 65 ++++++++++++++ 14 files changed, 499 insertions(+), 87 deletions(-) delete mode 100644 src/main/java/com/book_everywhere/auth/jwt/JWTUtil.java create mode 100644 src/main/java/com/book_everywhere/jwt/controller/RefreshController.java create mode 100644 src/main/java/com/book_everywhere/jwt/domain/Refresh.java create mode 100644 src/main/java/com/book_everywhere/jwt/dto/RefreshDto.java create mode 100644 src/main/java/com/book_everywhere/jwt/filter/CustomLogoutFilter.java rename src/main/java/com/book_everywhere/{oauth2 => jwt/filter}/CustomSuccessHandler.java (54%) rename src/main/java/com/book_everywhere/{auth/jwt/JWTFilter.java => jwt/filter/JwtFilter.java} (85%) create mode 100644 src/main/java/com/book_everywhere/jwt/repository/RefreshRepository.java create mode 100644 src/main/java/com/book_everywhere/jwt/service/RefreshService.java create mode 100644 src/main/java/com/book_everywhere/jwt/service/RefreshServiceImpl.java create mode 100644 src/main/java/com/book_everywhere/jwt/token/JwtProvider.java create mode 100644 src/main/java/com/book_everywhere/jwt/token/TokenType.java create mode 100644 src/test/java/com/book_everywhere/domain/jwt/service/RefreshSeriveTest.java diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index c6205b5..041a284 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -1,9 +1,11 @@ package com.book_everywhere.auth.config; -import com.book_everywhere.auth.jwt.JWTFilter; -import com.book_everywhere.auth.jwt.JWTUtil; +import com.book_everywhere.jwt.filter.CustomLogoutFilter; +import com.book_everywhere.jwt.filter.JwtFilter; +import com.book_everywhere.jwt.service.RefreshService; +import com.book_everywhere.jwt.token.JwtProvider; import com.book_everywhere.auth.service.CustomOAuth2UserService; -import com.book_everywhere.oauth2.CustomSuccessHandler; +import com.book_everywhere.jwt.filter.CustomSuccessHandler; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -14,10 +16,8 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.security.web.servlet.util.matcher.MvcRequestMatcher; +import org.springframework.security.web.authentication.logout.LogoutFilter; import org.springframework.web.cors.CorsConfigurationSource; -import org.springframework.web.servlet.handler.HandlerMappingIntrospector; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; @@ -30,7 +30,8 @@ public class SecurityConfig { private final CustomOAuth2UserService customOAuth2UserService; private final CustomSuccessHandler customSuccessHandler; - private final JWTUtil jwtUtil; + private final JwtProvider jwtProvider; + private final RefreshService refreshService; @Bean @@ -62,27 +63,24 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .csrf(AbstractHttpConfigurer::disable) .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) - .addFilterBefore(new JWTFilter(jwtUtil), OAuth2LoginAuthenticationFilter.class) + .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() - .requestMatchers( "/login").permitAll() - .requestMatchers( "/health").permitAll() - .requestMatchers( "/env").permitAll() - .requestMatchers( "/test/**").permitAll() - .requestMatchers( "/swagger-ui/**").permitAll() - .requestMatchers("/api/review").permitAll() - .requestMatchers("/api/map").permitAll() - .requestMatchers("/api/tags").permitAll() - .requestMatchers( "/api/data/**").permitAll() - .requestMatchers( "/api/**").hasAuthority("ROLE_MEMBER") - .requestMatchers( "/admin").hasAuthority("ROLE_MEMBER") + // 테스트 관련 url + .requestMatchers("/health","/env","/test/**","/swagger-ui/**").permitAll() + // 비회원도 볼수있는 url + .requestMatchers("/api/review","/api/map","/api/tags","/api/data/**").permitAll() + // 나머지 + .requestMatchers("/api/**").hasAuthority("ROLE_MEMBER") .anyRequest().authenticated() ) .oauth2Login(oauth2Login -> oauth2Login .userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig.userService(customOAuth2UserService)) - .successHandler(customSuccessHandler)) + .successHandler(customSuccessHandler) + ) + .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) ; return http.build(); } diff --git a/src/main/java/com/book_everywhere/auth/jwt/JWTUtil.java b/src/main/java/com/book_everywhere/auth/jwt/JWTUtil.java deleted file mode 100644 index f66b25a..0000000 --- a/src/main/java/com/book_everywhere/auth/jwt/JWTUtil.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.book_everywhere.auth.jwt; - - -import com.book_everywhere.auth.entity.Role; -import org.springframework.stereotype.Component; - -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; -import java.nio.charset.StandardCharsets; -import java.util.Date; - -import io.jsonwebtoken.Jwts; -import org.springframework.beans.factory.annotation.Value; - -@Component -public class JWTUtil { - - private SecretKey secretKey; - - public JWTUtil(@Value("${app.jwt.secret}") String secret) { - secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), Jwts.SIG.HS256.key().build().getAlgorithm()); - } - - public String getUsername(String token) { - return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("username", String.class); - } - - public Role getRole(String token) { - return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", Role.class); - } - - public Boolean isExpired(String token) { - return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date()); - } - - public String createJwt(String username, String role, Long expiredMs) { - return Jwts.builder() - .claim("username", username) - .claim("role", role) - .issuedAt(new Date(System.currentTimeMillis())) - .expiration(new Date(System.currentTimeMillis() + expiredMs)) - .signWith(secretKey) - .compact(); - } -} \ No newline at end of file diff --git a/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java b/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java new file mode 100644 index 0000000..45d7f30 --- /dev/null +++ b/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java @@ -0,0 +1,82 @@ +package com.book_everywhere.jwt.controller; + +import com.book_everywhere.jwt.dto.RefreshDto; +import com.book_everywhere.jwt.service.RefreshService; +import com.book_everywhere.jwt.token.JwtProvider; +import com.book_everywhere.common.dto.CMRespDto; +import com.book_everywhere.jwt.token.TokenType; +import io.jsonwebtoken.ExpiredJwtException; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + + +@RestController +@RequiredArgsConstructor +public class RefreshController { + + private final JwtProvider jwtProvider; + private final RefreshService refreshService; + + @PostMapping("/api/refresh") + public CMRespDto reissue(HttpServletRequest request, HttpServletResponse response) { + + //get refresh token + String refresh = null; + Cookie[] cookies = request.getCookies(); + for (Cookie cookie : cookies) { + if (cookie.getName().equals(TokenType.REFRESH.getType())) { + refresh = cookie.getValue(); + } + } + + if (refresh == null) { + //response status code + return new CMRespDto<>(HttpStatus.BAD_REQUEST, null, "refresh token null"); + } + + //expired check + try { + jwtProvider.isExpired(refresh); + } catch (ExpiredJwtException e) { + + //response status code + return new CMRespDto<>(HttpStatus.BAD_REQUEST, null, "refresh token expired"); + } + + // 토큰이 refresh인지 확인 (발급시 페이로드에 명시) + String category = jwtProvider.getCategory(refresh); + + if (!category.equals(TokenType.REFRESH.getType())) { + return new CMRespDto<>(HttpStatus.BAD_REQUEST, null, "invalid refresh token"); + } + + boolean isExist = refreshService.리프레시토큰조회(refresh); + if (!isExist) { + return new CMRespDto<>(HttpStatus.BAD_REQUEST, null, "invalid refresh token"); + } + + + String username = jwtProvider.getUsername(refresh); + String role = jwtProvider.getRole(refresh); + + //make new JWT + String newAccess = jwtProvider.createJwt(TokenType.ACCESS.getType(), username, role, TokenType.ACCESS.getExpirationTime()); + String newRefresh = jwtProvider.createJwt(TokenType.REFRESH.getType(), username, role, TokenType.REFRESH.getExpirationTime()); + + refreshService.리프레시토큰삭제(username); + refreshService.리프레시토큰생성(new RefreshDto(username, newRefresh, String.valueOf(TokenType.REFRESH.getExpirationTime()))); + + //response + response.setHeader(TokenType.ACCESS.getType(), newAccess); + response.addCookie(jwtProvider.createCookie(TokenType.REFRESH.getType(), newRefresh)); + + return new CMRespDto<>(HttpStatus.OK, null, "재발급 완료"); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/book_everywhere/jwt/domain/Refresh.java b/src/main/java/com/book_everywhere/jwt/domain/Refresh.java new file mode 100644 index 0000000..c75f9f8 --- /dev/null +++ b/src/main/java/com/book_everywhere/jwt/domain/Refresh.java @@ -0,0 +1,27 @@ +package com.book_everywhere.jwt.domain; + +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; + +@Builder +@AllArgsConstructor +@NoArgsConstructor +@Entity +@Getter +public class Refresh { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String username; + private String refresh; + private String expiration; + +} diff --git a/src/main/java/com/book_everywhere/jwt/dto/RefreshDto.java b/src/main/java/com/book_everywhere/jwt/dto/RefreshDto.java new file mode 100644 index 0000000..77b42bf --- /dev/null +++ b/src/main/java/com/book_everywhere/jwt/dto/RefreshDto.java @@ -0,0 +1,33 @@ +package com.book_everywhere.jwt.dto; + +import com.book_everywhere.jwt.domain.Refresh; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; + +import java.util.Date; + +@Data +@Builder +@AllArgsConstructor +public class RefreshDto { + private String username; + private String refresh; + private String expiredMs; + + public Refresh toEntity(Date date) { + return Refresh.builder() + .username(username) + .refresh(refresh) + .expiration(date.toString()) + .build(); + } + + public static RefreshDto toDto(Refresh refresh) { + return RefreshDto.builder() + .username(refresh.getUsername()) + .refresh(refresh.getRefresh()) + .expiredMs(refresh.getExpiration()) + .build(); + } +} diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomLogoutFilter.java b/src/main/java/com/book_everywhere/jwt/filter/CustomLogoutFilter.java new file mode 100644 index 0000000..e2d0e25 --- /dev/null +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomLogoutFilter.java @@ -0,0 +1,77 @@ +package com.book_everywhere.jwt.filter; + + +import com.book_everywhere.jwt.dto.RefreshDto; +import com.book_everywhere.jwt.service.RefreshService; +import com.book_everywhere.jwt.token.JwtProvider; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; + +import static com.book_everywhere.jwt.token.TokenType.REFRESH; + +@RequiredArgsConstructor +public class CustomLogoutFilter extends GenericFilterBean { + + private final JwtProvider jwtProvider; + private final RefreshService refreshService; + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + HttpServletRequest httpRequest = (HttpServletRequest) request; + HttpServletResponse httpResponse = (HttpServletResponse) response; + + if (isLogoutRequest(httpRequest)) { + handleLogout(httpRequest, httpResponse); + } else { + chain.doFilter(request, response); + } + } + + private boolean isLogoutRequest(HttpServletRequest request) { + return "POST".equalsIgnoreCase(request.getMethod()) && "/logout".equals(request.getRequestURI()); + } + + private void handleLogout(HttpServletRequest request, HttpServletResponse response) throws IOException { + String refreshToken = extractRefreshToken(request); + + if (refreshToken == null || !jwtProvider.validateToken(refreshToken)) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } + + if (!refreshService.리프레시토큰조회(refreshToken)) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } + RefreshDto refreshDto = refreshService.리프레시토큰객체조회(refreshToken); + refreshService.리프레시토큰삭제(refreshDto.getUsername()); + clearRefreshTokenCookie(response); + response.setStatus(HttpServletResponse.SC_OK); + } + + private String extractRefreshToken(HttpServletRequest request) { + if (request.getCookies() == null) return null; + for (Cookie cookie : request.getCookies()) { + if (REFRESH.getType().equals(cookie.getName())) { + return cookie.getValue(); + } + } + return null; + } + + private void clearRefreshTokenCookie(HttpServletResponse response) { + Cookie cookie = new Cookie(REFRESH.getType(), null); + cookie.setMaxAge(0); + cookie.setPath("/"); + response.addCookie(cookie); + } +} \ No newline at end of file diff --git a/src/main/java/com/book_everywhere/oauth2/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java similarity index 54% rename from src/main/java/com/book_everywhere/oauth2/CustomSuccessHandler.java rename to src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index 629d4ae..2e24caf 100644 --- a/src/main/java/com/book_everywhere/oauth2/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -1,12 +1,14 @@ -package com.book_everywhere.oauth2; +package com.book_everywhere.jwt.filter; import com.book_everywhere.auth.dto.CustomOAuth2User; -import com.book_everywhere.auth.jwt.JWTUtil; +import com.book_everywhere.jwt.dto.RefreshDto; +import com.book_everywhere.jwt.service.RefreshService; +import com.book_everywhere.jwt.token.JwtProvider; import jakarta.servlet.ServletException; -import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; @@ -16,11 +18,15 @@ import java.util.Collection; import java.util.Iterator; +import static com.book_everywhere.jwt.token.TokenType.ACCESS; +import static com.book_everywhere.jwt.token.TokenType.REFRESH; + @RequiredArgsConstructor @Component public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { - private final JWTUtil jwtUtil; + private final JwtProvider jwtProvider; + private final RefreshService refreshService; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { @@ -35,20 +41,17 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo GrantedAuthority auth = iterator.next(); String role = auth.getAuthority(); - String token = jwtUtil.createJwt(username, role, 60*60*60L); - - response.addCookie(createCookie("Authorization", token)); - response.sendRedirect("http://localhost:3000/"); - } + String access = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); + String refresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); - private Cookie createCookie(String key, String value) { + refreshService.리프레시토큰생성(new RefreshDto(username, refresh, String.valueOf(REFRESH.getExpirationTime()))); - Cookie cookie = new Cookie(key, value); - cookie.setMaxAge(60*60*60); - //cookie.setSecure(true); - cookie.setPath("/"); - cookie.setHttpOnly(true); - return cookie; +// response.addCookie(jwtProvider.createCookie("Authorization", refresh)); +// response.sendRedirect("http://localhost:3000/"); + response.setHeader(ACCESS.getType(), access); + response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); + response.setStatus(HttpStatus.OK.value()); } + } diff --git a/src/main/java/com/book_everywhere/auth/jwt/JWTFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java similarity index 85% rename from src/main/java/com/book_everywhere/auth/jwt/JWTFilter.java rename to src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index a9ca7d0..6c27ffe 100644 --- a/src/main/java/com/book_everywhere/auth/jwt/JWTFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -1,7 +1,9 @@ -package com.book_everywhere.auth.jwt; +package com.book_everywhere.jwt.filter; import com.book_everywhere.auth.dto.CustomOAuth2User; import com.book_everywhere.auth.dto.UserDto; +import com.book_everywhere.auth.entity.Role; +import com.book_everywhere.jwt.token.JwtProvider; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; @@ -16,9 +18,9 @@ import java.io.IOException; @RequiredArgsConstructor -public class JWTFilter extends OncePerRequestFilter { +public class JwtFilter extends OncePerRequestFilter { - private final JWTUtil jwtUtil; + private final JwtProvider jwtProvider; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { @@ -49,7 +51,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse String token = authorization; //토큰 소멸 시간 검증 - if (jwtUtil.isExpired(token)) { + if (jwtProvider.isExpired(token)) { System.out.println("token expired"); filterChain.doFilter(request, response); @@ -60,8 +62,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse //토큰에서 username과 role 획득 UserDto userDto = new UserDto(); - userDto.setNickname(jwtUtil.getUsername(token)); - userDto.setRole(jwtUtil.getRole(token)); + userDto.setNickname(jwtProvider.getUsername(token)); + userDto.setRole(Role.valueOf(jwtProvider.getRole(token))); //UserDetails에 회원 정보 객체 담기 diff --git a/src/main/java/com/book_everywhere/jwt/repository/RefreshRepository.java b/src/main/java/com/book_everywhere/jwt/repository/RefreshRepository.java new file mode 100644 index 0000000..6003412 --- /dev/null +++ b/src/main/java/com/book_everywhere/jwt/repository/RefreshRepository.java @@ -0,0 +1,15 @@ +package com.book_everywhere.jwt.repository; + +import com.book_everywhere.jwt.domain.Refresh; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface RefreshRepository extends JpaRepository { + Boolean existsByRefresh(String refresh); + + void deleteByRefresh(String refresh); + + //유저네임 기준으로 삭제 이러면 모든 곳에서 로그아웃됨. + void deleteByUsername(String username); + + Refresh findByRefresh(String refresh); +} diff --git a/src/main/java/com/book_everywhere/jwt/service/RefreshService.java b/src/main/java/com/book_everywhere/jwt/service/RefreshService.java new file mode 100644 index 0000000..4bd824d --- /dev/null +++ b/src/main/java/com/book_everywhere/jwt/service/RefreshService.java @@ -0,0 +1,11 @@ +package com.book_everywhere.jwt.service; + +import com.book_everywhere.jwt.domain.Refresh; +import com.book_everywhere.jwt.dto.RefreshDto; + +public interface RefreshService { + void 리프레시토큰삭제(String username); + boolean 리프레시토큰조회(String refresh); + RefreshDto 리프레시토큰객체조회(String refresh); + void 리프레시토큰생성(RefreshDto refreshDto); +} diff --git a/src/main/java/com/book_everywhere/jwt/service/RefreshServiceImpl.java b/src/main/java/com/book_everywhere/jwt/service/RefreshServiceImpl.java new file mode 100644 index 0000000..cb7bcc9 --- /dev/null +++ b/src/main/java/com/book_everywhere/jwt/service/RefreshServiceImpl.java @@ -0,0 +1,40 @@ +package com.book_everywhere.jwt.service; + +import com.book_everywhere.jwt.domain.Refresh; +import com.book_everywhere.jwt.dto.RefreshDto; +import com.book_everywhere.jwt.repository.RefreshRepository; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.Date; + +@Service +@Transactional +@RequiredArgsConstructor +public class RefreshServiceImpl implements RefreshService { + + private final RefreshRepository refreshRepository; + + @Override + public void 리프레시토큰삭제(String refresh) { + refreshRepository.deleteByRefresh(refresh); + } + + @Override + public boolean 리프레시토큰조회(String refresh) { + return refreshRepository.existsByRefresh(refresh); + } + + @Override + public void 리프레시토큰생성(RefreshDto refreshDto) { + Date date = new Date(System.currentTimeMillis() + refreshDto.getExpiredMs()); + refreshRepository.save(refreshDto.toEntity(date)); + } + + @Override + public RefreshDto 리프레시토큰객체조회(String refresh) { + Refresh token =refreshRepository.findByRefresh(refresh); + return RefreshDto.toDto(token); + } +} diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java new file mode 100644 index 0000000..53eb54c --- /dev/null +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -0,0 +1,86 @@ +package com.book_everywhere.jwt.token; + + +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.MalformedJwtException; +import io.jsonwebtoken.UnsupportedJwtException; +import jakarta.servlet.http.Cookie; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.util.Date; + +import io.jsonwebtoken.Jwts; +import org.springframework.beans.factory.annotation.Value; + +@Component +public class JwtProvider { + + private final Logger logger = LoggerFactory.getLogger(JwtProvider.class); + private SecretKey secretKey; + + public JwtProvider(@Value("${app.jwt.secret}") String secret) { + secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), Jwts.SIG.HS256.key().build().getAlgorithm()); + } + + public String getUsername(String token) { + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("username", String.class); + } + + public String getRole(String token) { + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); + } + public String getCategory(String token) { + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("category", String.class); + } + public Boolean isExpired(String token) { + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date()); + } + + public String createJwt(String category, String username, String role, Long expiredMs) { + return Jwts.builder() + .claim("category", category) + .claim("username", username) + .claim("role", role) + .issuedAt(new Date(System.currentTimeMillis())) + .expiration(new Date(System.currentTimeMillis() + expiredMs)) + .signWith(secretKey) + .compact(); + } + public Cookie createCookie(String key, String value) { + + Cookie cookie = new Cookie(key, value); + cookie.setMaxAge(24 * 60 * 60); + //cookie.setSecure(true); + //cookie.setPath("/"); + cookie.setHttpOnly(true); + + return cookie; + } + + public boolean validateToken(String token) { + try { + Jwts.parser() + .setSigningKey(secretKey) + .build() + .parseClaimsJws(token); + return true; + } catch (ExpiredJwtException e) { + logger.info("만료된 JWT 토큰입니다."); + } catch (UnsupportedJwtException e) { + logger.info("지원되지 않는 JWT 토큰입니다."); + } catch (MalformedJwtException e) { + logger.info("잘못된 형식의 JWT 토큰입니다."); + } catch (SecurityException e) { + logger.info("잘못된 JWT 서명입니다."); + } catch (IllegalArgumentException e) { + logger.info("JWT 토큰이 잘못되었습니다."); + } + // 위의 예외 중 하나라도 발생했다면, 토큰이 유효하지 않음을 의미합니다. + return false; + } +} \ No newline at end of file diff --git a/src/main/java/com/book_everywhere/jwt/token/TokenType.java b/src/main/java/com/book_everywhere/jwt/token/TokenType.java new file mode 100644 index 0000000..1df79dd --- /dev/null +++ b/src/main/java/com/book_everywhere/jwt/token/TokenType.java @@ -0,0 +1,18 @@ +package com.book_everywhere.jwt.token; + +import lombok.Getter; + +@Getter +public enum TokenType { + ACCESS("access", 600000L), + REFRESH("refresh", 86400000L); + + private final String type; + private final Long expirationTime; + + TokenType(String type, Long expirationTime) { + this.type = type; + this.expirationTime = expirationTime; + } + +} diff --git a/src/test/java/com/book_everywhere/domain/jwt/service/RefreshSeriveTest.java b/src/test/java/com/book_everywhere/domain/jwt/service/RefreshSeriveTest.java new file mode 100644 index 0000000..284f580 --- /dev/null +++ b/src/test/java/com/book_everywhere/domain/jwt/service/RefreshSeriveTest.java @@ -0,0 +1,65 @@ +package com.book_everywhere.domain.jwt.service; + + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.*; + +import com.book_everywhere.jwt.dto.RefreshDto; +import com.book_everywhere.jwt.repository.RefreshRepository; +import com.book_everywhere.jwt.service.RefreshService; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class RefreshServiceTest { + + @Autowired + private RefreshService refreshService; + + @Autowired + private RefreshRepository refreshRepository; + + @Test + @DisplayName("리프레시 토큰 생성 테스트") + void 리프레시토큰생성_테스트() { + RefreshDto refreshDto = new RefreshDto("ID", "token",String.valueOf(1000L)); // 1000L은 토큰 만료 시간 + given(refreshRepository.save(any())).willReturn(any()); + + // When + refreshService.리프레시토큰생성(refreshDto); + + // Then + verify(refreshRepository).save(any()); + } + + @Test + @DisplayName("리프레시 토큰 조회 테스트") + void 리프레시토큰조회_테스트() { + // Given + String refreshToken = "token"; + given(refreshRepository.existsByRefresh(refreshToken)).willReturn(true); + + // When + boolean exists = refreshService.리프레시토큰조회(refreshToken); + + // Then + assertTrue(exists); + } + + @Test + @DisplayName("리프레시 토큰 삭제 테스트") + void 리프레시토큰삭제_테스트() { + // Given + String refreshToken = "token"; + + // When + refreshService.리프레시토큰삭제(refreshToken); + + // Then + verify(refreshRepository).deleteByRefresh(refreshToken); + // 삭제 메소드가 해당 토큰으로 호출되었는지 확인 + } +} From 6f66da52e310142cb2c74e6faedbdecf40efc80f Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 03:14:36 +0900 Subject: [PATCH 05/51] =?UTF-8?q?feat=20:=20JWT=20Refresh=20=ED=86=A0?= =?UTF-8?q?=ED=81=B0=20=EC=83=9D=EC=84=B1/=EC=82=AD=EC=A0=9C/=EC=9E=AC?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../book_everywhere/jwt/filter/JwtFilter.java | 58 +++++++++---------- .../jwt/repository/RefreshRepository.java | 2 - .../{ => impl}/RefreshServiceImpl.java | 7 ++- .../jwt/token/JwtProvider.java | 7 ++- .../domain/jwt/service/RefreshSeriveTest.java | 14 +++-- 5 files changed, 45 insertions(+), 43 deletions(-) rename src/main/java/com/book_everywhere/jwt/service/{ => impl}/RefreshServiceImpl.java (83%) diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index 6c27ffe..9069c21 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -16,6 +16,9 @@ import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; +import java.io.PrintWriter; + +import static com.book_everywhere.jwt.token.TokenType.ACCESS; @RequiredArgsConstructor public class JwtFilter extends OncePerRequestFilter { @@ -25,46 +28,21 @@ public class JwtFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - //cookie들을 불러온 뒤 Authorization Key에 담긴 쿠키를 찾음 - String authorization = null; - Cookie[] cookies = request.getCookies(); - for (Cookie cookie : cookies) { - - System.out.println(cookie.getName()); - if (cookie.getName().equals("Authorization")) { - - authorization = cookie.getValue(); - } - } - - //Authorization 헤더 검증 - if (authorization == null) { + String accessToken = request.getHeader(ACCESS.getType()); - System.out.println("token null"); + if (accessToken == null) { filterChain.doFilter(request, response); - - //조건이 해당되면 메소드 종료 (필수) return; } - //토큰 - String token = authorization; - - //토큰 소멸 시간 검증 - if (jwtProvider.isExpired(token)) { - - System.out.println("token expired"); - filterChain.doFilter(request, response); - - //조건이 해당되면 메소드 종료 (필수) + if (!validateToken(response, accessToken)) { return; } //토큰에서 username과 role 획득 UserDto userDto = new UserDto(); - userDto.setNickname(jwtProvider.getUsername(token)); - userDto.setRole(Role.valueOf(jwtProvider.getRole(token))); - + userDto.setNickname(jwtProvider.getUsername(accessToken)); + userDto.setRole(Role.valueOf(jwtProvider.getRole(accessToken))); //UserDetails에 회원 정보 객체 담기 CustomOAuth2User customOAuth2User = new CustomOAuth2User(userDto); @@ -76,4 +54,24 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse filterChain.doFilter(request, response); } + + private boolean validateToken(HttpServletResponse response, String accessToken) throws IOException { + try { + if (jwtProvider.isExpired(accessToken) || !ACCESS.getType().equals(jwtProvider.getCategory(accessToken))) { + sendErrorResponse(response, "Invalid or expired access token", HttpServletResponse.SC_UNAUTHORIZED); + return false; + } + } catch (Exception e) { // 넓은 범위의 예외 처리를 통해 다양한 에러 상황을 처리할 수 있습니다. + sendErrorResponse(response, "Token validation error", HttpServletResponse.SC_UNAUTHORIZED); + return false; + } + return true; + } + + private void sendErrorResponse(HttpServletResponse response, String message, int status) throws IOException { + response.setStatus(status); + try (PrintWriter writer = response.getWriter()) { + writer.print(message); + } + } } \ No newline at end of file diff --git a/src/main/java/com/book_everywhere/jwt/repository/RefreshRepository.java b/src/main/java/com/book_everywhere/jwt/repository/RefreshRepository.java index 6003412..60b36f1 100644 --- a/src/main/java/com/book_everywhere/jwt/repository/RefreshRepository.java +++ b/src/main/java/com/book_everywhere/jwt/repository/RefreshRepository.java @@ -6,8 +6,6 @@ public interface RefreshRepository extends JpaRepository { Boolean existsByRefresh(String refresh); - void deleteByRefresh(String refresh); - //유저네임 기준으로 삭제 이러면 모든 곳에서 로그아웃됨. void deleteByUsername(String username); diff --git a/src/main/java/com/book_everywhere/jwt/service/RefreshServiceImpl.java b/src/main/java/com/book_everywhere/jwt/service/impl/RefreshServiceImpl.java similarity index 83% rename from src/main/java/com/book_everywhere/jwt/service/RefreshServiceImpl.java rename to src/main/java/com/book_everywhere/jwt/service/impl/RefreshServiceImpl.java index cb7bcc9..6691a4d 100644 --- a/src/main/java/com/book_everywhere/jwt/service/RefreshServiceImpl.java +++ b/src/main/java/com/book_everywhere/jwt/service/impl/RefreshServiceImpl.java @@ -1,8 +1,9 @@ -package com.book_everywhere.jwt.service; +package com.book_everywhere.jwt.service.impl; import com.book_everywhere.jwt.domain.Refresh; import com.book_everywhere.jwt.dto.RefreshDto; import com.book_everywhere.jwt.repository.RefreshRepository; +import com.book_everywhere.jwt.service.RefreshService; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -17,8 +18,8 @@ public class RefreshServiceImpl implements RefreshService { private final RefreshRepository refreshRepository; @Override - public void 리프레시토큰삭제(String refresh) { - refreshRepository.deleteByRefresh(refresh); + public void 리프레시토큰삭제(String username) { + refreshRepository.deleteByUsername(username); } @Override diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index 53eb54c..5fd8fb0 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -34,14 +34,16 @@ public String getUsername(String token) { public String getRole(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); } + public String getCategory(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("category", String.class); } + public Boolean isExpired(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date()); } - public String createJwt(String category, String username, String role, Long expiredMs) { + public String createJwt(String category, String username, String role, Long expiredMs) { return Jwts.builder() .claim("category", category) .claim("username", username) @@ -51,12 +53,13 @@ public String createJwt(String category, String username, String role, Long expi .signWith(secretKey) .compact(); } + public Cookie createCookie(String key, String value) { Cookie cookie = new Cookie(key, value); cookie.setMaxAge(24 * 60 * 60); //cookie.setSecure(true); - //cookie.setPath("/"); + cookie.setPath("/"); cookie.setHttpOnly(true); return cookie; diff --git a/src/test/java/com/book_everywhere/domain/jwt/service/RefreshSeriveTest.java b/src/test/java/com/book_everywhere/domain/jwt/service/RefreshSeriveTest.java index 284f580..7867b00 100644 --- a/src/test/java/com/book_everywhere/domain/jwt/service/RefreshSeriveTest.java +++ b/src/test/java/com/book_everywhere/domain/jwt/service/RefreshSeriveTest.java @@ -23,7 +23,7 @@ class RefreshServiceTest { private RefreshRepository refreshRepository; @Test - @DisplayName("리프레시 토큰 생성 테스트") + @DisplayName("Service_리프레시 토큰 생성 테스트") void 리프레시토큰생성_테스트() { RefreshDto refreshDto = new RefreshDto("ID", "token",String.valueOf(1000L)); // 1000L은 토큰 만료 시간 given(refreshRepository.save(any())).willReturn(any()); @@ -36,7 +36,7 @@ class RefreshServiceTest { } @Test - @DisplayName("리프레시 토큰 조회 테스트") + @DisplayName("Service_리프레시 토큰 조회 테스트") void 리프레시토큰조회_테스트() { // Given String refreshToken = "token"; @@ -50,16 +50,18 @@ class RefreshServiceTest { } @Test - @DisplayName("리프레시 토큰 삭제 테스트") + @DisplayName("Service_리프레시 토큰 삭제 테스트") void 리프레시토큰삭제_테스트() { // Given - String refreshToken = "token"; + RefreshDto refreshDto = new RefreshDto("ID", "token",String.valueOf(1000L)); // 1000L은 토큰 만료 시간 + given(refreshRepository.save(any())).willReturn(any()); // When - refreshService.리프레시토큰삭제(refreshToken); + refreshService.리프레시토큰생성(refreshDto); + refreshService.리프레시토큰삭제(refreshDto.getUsername()); // Then - verify(refreshRepository).deleteByRefresh(refreshToken); + verify(refreshRepository).deleteByUsername(refreshDto.getUsername()); // 삭제 메소드가 해당 토큰으로 호출되었는지 확인 } } From 8348edee3ae2f2c13cb2b87b28b6ae7b758c5116 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 03:54:08 +0900 Subject: [PATCH 06/51] =?UTF-8?q?feat=20:=20JWT=20Refresh=20=ED=86=A0?= =?UTF-8?q?=ED=81=B0=20=EC=83=9D=EC=84=B1/=EC=82=AD=EC=A0=9C/=EC=9E=AC?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 1 - .../auth/config/SecurityConfig.java | 2 +- .../book_everywhere/jwt/domain/Refresh.java | 6 ++---- .../jwt/filter/CustomLogoutFilter.java | 2 ++ .../jwt/token/JwtProvider.java | 8 ++++---- .../book_everywhere/likes/entity/Likes.java | 1 + ...eriveTest.java => RefreshServiceTest.java} | 20 +++++++++++-------- 7 files changed, 22 insertions(+), 18 deletions(-) rename src/test/java/com/book_everywhere/domain/jwt/service/{RefreshSeriveTest.java => RefreshServiceTest.java} (81%) diff --git a/build.gradle b/build.gradle index 8bfa4f1..c9fa796 100644 --- a/build.gradle +++ b/build.gradle @@ -42,7 +42,6 @@ dependencies { implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' //log를 위한 추가 - //test를 위한 추가 runtimeOnly 'com.h2database:h2' diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 041a284..7f30027 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -64,6 +64,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) + .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() // 테스트 관련 url @@ -80,7 +81,6 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { userInfoEndpointConfig.userService(customOAuth2UserService)) .successHandler(customSuccessHandler) ) - .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) ; return http.build(); } diff --git a/src/main/java/com/book_everywhere/jwt/domain/Refresh.java b/src/main/java/com/book_everywhere/jwt/domain/Refresh.java index c75f9f8..d63685a 100644 --- a/src/main/java/com/book_everywhere/jwt/domain/Refresh.java +++ b/src/main/java/com/book_everywhere/jwt/domain/Refresh.java @@ -1,9 +1,6 @@ package com.book_everywhere.jwt.domain; -import jakarta.persistence.Entity; -import jakarta.persistence.GeneratedValue; -import jakarta.persistence.GenerationType; -import jakarta.persistence.Id; +import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; @@ -18,6 +15,7 @@ public class Refresh { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "refresh_id") private Long id; private String username; diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomLogoutFilter.java b/src/main/java/com/book_everywhere/jwt/filter/CustomLogoutFilter.java index e2d0e25..a890ccc 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomLogoutFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomLogoutFilter.java @@ -12,6 +12,7 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; import org.springframework.web.filter.GenericFilterBean; import java.io.IOException; @@ -19,6 +20,7 @@ import static com.book_everywhere.jwt.token.TokenType.REFRESH; @RequiredArgsConstructor +@Component public class CustomLogoutFilter extends GenericFilterBean { private final JwtProvider jwtProvider; diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index 5fd8fb0..ed18706 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -1,12 +1,14 @@ package com.book_everywhere.jwt.token; - import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.Jwts; import io.jsonwebtoken.MalformedJwtException; import io.jsonwebtoken.UnsupportedJwtException; import jakarta.servlet.http.Cookie; +import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.crypto.SecretKey; @@ -14,9 +16,7 @@ import java.nio.charset.StandardCharsets; import java.util.Date; -import io.jsonwebtoken.Jwts; -import org.springframework.beans.factory.annotation.Value; - +@RequiredArgsConstructor @Component public class JwtProvider { diff --git a/src/main/java/com/book_everywhere/likes/entity/Likes.java b/src/main/java/com/book_everywhere/likes/entity/Likes.java index 9baf52d..a87f417 100644 --- a/src/main/java/com/book_everywhere/likes/entity/Likes.java +++ b/src/main/java/com/book_everywhere/likes/entity/Likes.java @@ -27,6 +27,7 @@ public class Likes extends BaseTimeEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "like_id") private Long id; @ManyToOne(fetch = FetchType.LAZY) diff --git a/src/test/java/com/book_everywhere/domain/jwt/service/RefreshSeriveTest.java b/src/test/java/com/book_everywhere/domain/jwt/service/RefreshServiceTest.java similarity index 81% rename from src/test/java/com/book_everywhere/domain/jwt/service/RefreshSeriveTest.java rename to src/test/java/com/book_everywhere/domain/jwt/service/RefreshServiceTest.java index 7867b00..7da9406 100644 --- a/src/test/java/com/book_everywhere/domain/jwt/service/RefreshSeriveTest.java +++ b/src/test/java/com/book_everywhere/domain/jwt/service/RefreshServiceTest.java @@ -1,10 +1,5 @@ package com.book_everywhere.domain.jwt.service; - -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.*; - import com.book_everywhere.jwt.dto.RefreshDto; import com.book_everywhere.jwt.repository.RefreshRepository; import com.book_everywhere.jwt.service.RefreshService; @@ -12,9 +7,16 @@ import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.transaction.annotation.Transactional; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.verify; @SpringBootTest -class RefreshServiceTest { +@Transactional +public class RefreshServiceTest { @Autowired private RefreshService refreshService; @@ -25,7 +27,7 @@ class RefreshServiceTest { @Test @DisplayName("Service_리프레시 토큰 생성 테스트") void 리프레시토큰생성_테스트() { - RefreshDto refreshDto = new RefreshDto("ID", "token",String.valueOf(1000L)); // 1000L은 토큰 만료 시간 + RefreshDto refreshDto = new RefreshDto("ID", "token", String.valueOf(1000L)); // 1000L은 토큰 만료 시간 given(refreshRepository.save(any())).willReturn(any()); // When @@ -53,7 +55,7 @@ class RefreshServiceTest { @DisplayName("Service_리프레시 토큰 삭제 테스트") void 리프레시토큰삭제_테스트() { // Given - RefreshDto refreshDto = new RefreshDto("ID", "token",String.valueOf(1000L)); // 1000L은 토큰 만료 시간 + RefreshDto refreshDto = new RefreshDto("ID", "token", String.valueOf(1000L)); // 1000L은 토큰 만료 시간 given(refreshRepository.save(any())).willReturn(any()); // When @@ -64,4 +66,6 @@ class RefreshServiceTest { verify(refreshRepository).deleteByUsername(refreshDto.getUsername()); // 삭제 메소드가 해당 토큰으로 호출되었는지 확인 } + + } From d3d2bb63ac1b170dcaf44ceef2977edd84bec23c Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 04:09:49 +0900 Subject: [PATCH 07/51] =?UTF-8?q?feat=20:=20JWT=20Refresh=20=ED=86=A0?= =?UTF-8?q?=ED=81=B0=20=EC=83=9D=EC=84=B1/=EC=82=AD=EC=A0=9C/=EC=9E=AC?= =?UTF-8?q?=EC=83=9D=EC=84=B1=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 5 +---- .../book_everywhere/auth/config/SecurityConfig.java | 2 +- src/main/resources/templates/admin.html | 10 ---------- src/main/resources/templates/login.html | 12 ------------ 4 files changed, 2 insertions(+), 27 deletions(-) delete mode 100644 src/main/resources/templates/admin.html delete mode 100644 src/main/resources/templates/login.html diff --git a/.gitignore b/.gitignore index e2ea27d..a72a914 100644 --- a/.gitignore +++ b/.gitignore @@ -6,11 +6,8 @@ build/ !**/src/test/**/build/ src/main/resources/*.yml -!application.yml src/test/resources/*.yml -!application.yml - - +src/main/resources/templates/*.html ### STS ### .apt_generated diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 7f30027..76e6d58 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -68,7 +68,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() // 테스트 관련 url - .requestMatchers("/health","/env","/test/**","/swagger-ui/**").permitAll() + .requestMatchers("/health","/env","/test/**","/swagger-ui/**","/login").permitAll() // 비회원도 볼수있는 url .requestMatchers("/api/review","/api/map","/api/tags","/api/data/**").permitAll() // 나머지 diff --git a/src/main/resources/templates/admin.html b/src/main/resources/templates/admin.html deleted file mode 100644 index 75ea237..0000000 --- a/src/main/resources/templates/admin.html +++ /dev/null @@ -1,10 +0,0 @@ - - - - - Title - - -완료 - - \ No newline at end of file diff --git a/src/main/resources/templates/login.html b/src/main/resources/templates/login.html deleted file mode 100644 index 868e14a..0000000 --- a/src/main/resources/templates/login.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - Title - - - - 카카오톡으로 간편 로그인 - - - \ No newline at end of file From 72883af77931ae01e4d75ee4a02b463b3db23be1 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 04:37:54 +0900 Subject: [PATCH 08/51] =?UTF-8?q?feat=20:=20JWT=20=EA=B8=B0=EB=B0=98=20?= =?UTF-8?q?=EC=84=B8=EC=85=98=20=EC=9D=B8=EC=A6=9D=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/book_everywhere/auth/config/SecurityConfig.java | 2 +- src/main/java/com/book_everywhere/jwt/domain/Refresh.java | 3 ++- src/main/java/com/book_everywhere/jwt/token/JwtProvider.java | 5 +---- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 76e6d58..7f30027 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -68,7 +68,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() // 테스트 관련 url - .requestMatchers("/health","/env","/test/**","/swagger-ui/**","/login").permitAll() + .requestMatchers("/health","/env","/test/**","/swagger-ui/**").permitAll() // 비회원도 볼수있는 url .requestMatchers("/api/review","/api/map","/api/tags","/api/data/**").permitAll() // 나머지 diff --git a/src/main/java/com/book_everywhere/jwt/domain/Refresh.java b/src/main/java/com/book_everywhere/jwt/domain/Refresh.java index d63685a..b624aba 100644 --- a/src/main/java/com/book_everywhere/jwt/domain/Refresh.java +++ b/src/main/java/com/book_everywhere/jwt/domain/Refresh.java @@ -1,5 +1,6 @@ package com.book_everywhere.jwt.domain; +import com.book_everywhere.common.entity.BaseTimeEntity; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; @@ -11,7 +12,7 @@ @NoArgsConstructor @Entity @Getter -public class Refresh { +public class Refresh extends BaseTimeEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index ed18706..efd59a1 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -1,9 +1,6 @@ package com.book_everywhere.jwt.token; -import io.jsonwebtoken.ExpiredJwtException; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.MalformedJwtException; -import io.jsonwebtoken.UnsupportedJwtException; +import io.jsonwebtoken.*; import jakarta.servlet.http.Cookie; import lombok.RequiredArgsConstructor; import org.slf4j.Logger; From 5a08c3113cac5345d26796fe471b461950f280a7 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 04:54:32 +0900 Subject: [PATCH 09/51] =?UTF-8?q?feat=20:=20JWT=20=EA=B8=B0=EB=B0=98=20?= =?UTF-8?q?=EC=84=B8=EC=85=98=20=EC=9D=B8=EC=A6=9D=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java | 1 - src/main/java/com/book_everywhere/jwt/token/JwtProvider.java | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index 9069c21..8fccc30 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -6,7 +6,6 @@ import com.book_everywhere.jwt.token.JwtProvider; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; -import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index efd59a1..90c3cf3 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -56,7 +56,7 @@ public Cookie createCookie(String key, String value) { Cookie cookie = new Cookie(key, value); cookie.setMaxAge(24 * 60 * 60); //cookie.setSecure(true); - cookie.setPath("/"); +// cookie.setPath("/"); cookie.setHttpOnly(true); return cookie; From fce8950de67523fdac136b8cfdec4b74c16c8e5b Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 05:10:47 +0900 Subject: [PATCH 10/51] =?UTF-8?q?feat=20:=20JWT=20=EA=B8=B0=EB=B0=98=20?= =?UTF-8?q?=EC=84=B8=EC=85=98=20=EC=9D=B8=EC=A6=9D=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jwt/controller/RefreshController.java | 19 +++++++++++-------- .../book_everywhere/jwt/dto/RefreshDto.java | 4 ++-- .../jwt/filter/CustomSuccessHandler.java | 4 ++-- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java b/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java index 45d7f30..deb4ffc 100644 --- a/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java +++ b/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java @@ -14,6 +14,9 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; +import static com.book_everywhere.jwt.token.TokenType.ACCESS; +import static com.book_everywhere.jwt.token.TokenType.REFRESH; + @RestController @RequiredArgsConstructor @@ -29,7 +32,7 @@ public CMRespDto reissue(HttpServletRequest request, HttpServletResponse resp String refresh = null; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { - if (cookie.getName().equals(TokenType.REFRESH.getType())) { + if (cookie.getName().equals(REFRESH.getType())) { refresh = cookie.getValue(); } } @@ -51,7 +54,7 @@ public CMRespDto reissue(HttpServletRequest request, HttpServletResponse resp // 토큰이 refresh인지 확인 (발급시 페이로드에 명시) String category = jwtProvider.getCategory(refresh); - if (!category.equals(TokenType.REFRESH.getType())) { + if (!category.equals(REFRESH.getType())) { return new CMRespDto<>(HttpStatus.BAD_REQUEST, null, "invalid refresh token"); } @@ -65,15 +68,15 @@ public CMRespDto reissue(HttpServletRequest request, HttpServletResponse resp String role = jwtProvider.getRole(refresh); //make new JWT - String newAccess = jwtProvider.createJwt(TokenType.ACCESS.getType(), username, role, TokenType.ACCESS.getExpirationTime()); - String newRefresh = jwtProvider.createJwt(TokenType.REFRESH.getType(), username, role, TokenType.REFRESH.getExpirationTime()); + String newAccess = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); + String newRefresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); - refreshService.리프레시토큰삭제(username); - refreshService.리프레시토큰생성(new RefreshDto(username, newRefresh, String.valueOf(TokenType.REFRESH.getExpirationTime()))); + refreshService.리프레시토큰삭제(refresh); + refreshService.리프레시토큰생성(new RefreshDto(username, newRefresh, REFRESH.getExpirationTime())); //response - response.setHeader(TokenType.ACCESS.getType(), newAccess); - response.addCookie(jwtProvider.createCookie(TokenType.REFRESH.getType(), newRefresh)); + response.setHeader(ACCESS.getType(), newAccess); + response.addCookie(jwtProvider.createCookie(REFRESH.getType(), newRefresh)); return new CMRespDto<>(HttpStatus.OK, null, "재발급 완료"); } diff --git a/src/main/java/com/book_everywhere/jwt/dto/RefreshDto.java b/src/main/java/com/book_everywhere/jwt/dto/RefreshDto.java index 77b42bf..6129a5d 100644 --- a/src/main/java/com/book_everywhere/jwt/dto/RefreshDto.java +++ b/src/main/java/com/book_everywhere/jwt/dto/RefreshDto.java @@ -13,7 +13,7 @@ public class RefreshDto { private String username; private String refresh; - private String expiredMs; + private Long expiredMs; public Refresh toEntity(Date date) { return Refresh.builder() @@ -27,7 +27,7 @@ public static RefreshDto toDto(Refresh refresh) { return RefreshDto.builder() .username(refresh.getUsername()) .refresh(refresh.getRefresh()) - .expiredMs(refresh.getExpiration()) + .expiredMs(Long.parseLong(refresh.getExpiration())) .build(); } } diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index 2e24caf..daa7b39 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -44,13 +44,13 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo String access = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); String refresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); - refreshService.리프레시토큰생성(new RefreshDto(username, refresh, String.valueOf(REFRESH.getExpirationTime()))); - + refreshService.리프레시토큰생성(new RefreshDto(username, refresh, REFRESH.getExpirationTime())); // response.addCookie(jwtProvider.createCookie("Authorization", refresh)); // response.sendRedirect("http://localhost:3000/"); response.setHeader(ACCESS.getType(), access); response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); + response.sendRedirect("https://www.bookeverywhere.site/"); response.setStatus(HttpStatus.OK.value()); } From 32689f2cf442a2862be554ed195d126f34a2ad48 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 05:23:34 +0900 Subject: [PATCH 11/51] =?UTF-8?q?feat=20:=20JWT=20=EA=B8=B0=EB=B0=98=20?= =?UTF-8?q?=EC=84=B8=EC=85=98=20=EC=9D=B8=EC=A6=9D=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jwt/controller/RefreshController.java | 3 ++- .../jwt/filter/CustomSuccessHandler.java | 9 ++++++++- .../book_everywhere/jwt/filter/JwtFilter.java | 2 +- .../book_everywhere/jwt/token/JwtProvider.java | 16 +++++++++++----- 4 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java b/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java index deb4ffc..28bf94b 100644 --- a/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java +++ b/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java @@ -1,5 +1,6 @@ package com.book_everywhere.jwt.controller; +import com.book_everywhere.auth.entity.Role; import com.book_everywhere.jwt.dto.RefreshDto; import com.book_everywhere.jwt.service.RefreshService; import com.book_everywhere.jwt.token.JwtProvider; @@ -65,7 +66,7 @@ public CMRespDto reissue(HttpServletRequest request, HttpServletResponse resp String username = jwtProvider.getUsername(refresh); - String role = jwtProvider.getRole(refresh); + Role role = jwtProvider.getRole(refresh); //make new JWT String newAccess = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index daa7b39..55839ff 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -1,6 +1,7 @@ package com.book_everywhere.jwt.filter; import com.book_everywhere.auth.dto.CustomOAuth2User; +import com.book_everywhere.auth.entity.Role; import com.book_everywhere.jwt.dto.RefreshDto; import com.book_everywhere.jwt.service.RefreshService; import com.book_everywhere.jwt.token.JwtProvider; @@ -8,6 +9,8 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; @@ -25,6 +28,7 @@ @Component public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { + private static final Logger logger = LoggerFactory.getLogger(CustomSuccessHandler.class); private final JwtProvider jwtProvider; private final RefreshService refreshService; @@ -39,7 +43,10 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo Collection authorities = authentication.getAuthorities(); Iterator iterator = authorities.iterator(); GrantedAuthority auth = iterator.next(); - String role = auth.getAuthority(); + Role role = Role.valueOf(auth.getAuthority()); + logger.debug("------------------------"); + logger.debug("Role: {}", role); + logger.debug("------------------------"); String access = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); String refresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index 8fccc30..4320131 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -41,7 +41,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse //토큰에서 username과 role 획득 UserDto userDto = new UserDto(); userDto.setNickname(jwtProvider.getUsername(accessToken)); - userDto.setRole(Role.valueOf(jwtProvider.getRole(accessToken))); + userDto.setRole(jwtProvider.getRole(accessToken)); //UserDetails에 회원 정보 객체 담기 CustomOAuth2User customOAuth2User = new CustomOAuth2User(userDto); diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index 90c3cf3..1f60130 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -1,5 +1,6 @@ package com.book_everywhere.jwt.token; +import com.book_everywhere.auth.entity.Role; import io.jsonwebtoken.*; import jakarta.servlet.http.Cookie; import lombok.RequiredArgsConstructor; @@ -28,8 +29,8 @@ public String getUsername(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("username", String.class); } - public String getRole(String token) { - return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); + public Role getRole(String token) { + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", Role.class); } public String getCategory(String token) { @@ -40,15 +41,20 @@ public Boolean isExpired(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date()); } - public String createJwt(String category, String username, String role, Long expiredMs) { - return Jwts.builder() + public String createJwt(String category, String username, Role role, Long expiredMs) { + String jwt = Jwts.builder() .claim("category", category) .claim("username", username) - .claim("role", role) + .claim("role", role.toString()) .issuedAt(new Date(System.currentTimeMillis())) .expiration(new Date(System.currentTimeMillis() + expiredMs)) .signWith(secretKey) .compact(); + + // 생성된 JWT를 로그에 출력 + System.out.println("Created JWT: " + jwt); + + return jwt; } public Cookie createCookie(String key, String value) { From 129d010d0952316f6ce784a09b69886b6987977c Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 05:26:36 +0900 Subject: [PATCH 12/51] =?UTF-8?q?feat=20:=20JWT=20=EA=B8=B0=EB=B0=98=20?= =?UTF-8?q?=EC=84=B8=EC=85=98=20=EC=9D=B8=EC=A6=9D=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/book_everywhere/auth/config/SecurityConfig.java | 2 +- src/main/java/com/book_everywhere/jwt/token/JwtProvider.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 7f30027..041a284 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -64,7 +64,6 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) - .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() // 테스트 관련 url @@ -81,6 +80,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { userInfoEndpointConfig.userService(customOAuth2UserService)) .successHandler(customSuccessHandler) ) + .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) ; return http.build(); } diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index 1f60130..6287777 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -14,11 +14,11 @@ import java.nio.charset.StandardCharsets; import java.util.Date; -@RequiredArgsConstructor @Component public class JwtProvider { private final Logger logger = LoggerFactory.getLogger(JwtProvider.class); + private SecretKey secretKey; public JwtProvider(@Value("${app.jwt.secret}") String secret) { From 2182339d72d2bb46561f410299b9470d8a5cf646 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 05:37:28 +0900 Subject: [PATCH 13/51] =?UTF-8?q?feat=20:=20JWT=20=EA=B8=B0=EB=B0=98=20?= =?UTF-8?q?=EC=84=B8=EC=85=98=20=EC=9D=B8=EC=A6=9D=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/book_everywhere/jwt/filter/CustomSuccessHandler.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index 55839ff..1df564d 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -43,7 +43,9 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo Collection authorities = authentication.getAuthorities(); Iterator iterator = authorities.iterator(); GrantedAuthority auth = iterator.next(); + logger.info("Role: {}", auth.getAuthority()); Role role = Role.valueOf(auth.getAuthority()); + logger.debug("------------------------"); logger.debug("Role: {}", role); logger.debug("------------------------"); From 3a987d8370ca1e34aaccad9ca21fd75dd51bc970 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 05:38:08 +0900 Subject: [PATCH 14/51] =?UTF-8?q?feat=20:=20JWT=20=EA=B8=B0=EB=B0=98=20?= =?UTF-8?q?=EC=84=B8=EC=85=98=20=EC=9D=B8=EC=A6=9D=20=EA=B5=AC=ED=98=84=20?= =?UTF-8?q?=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/book_everywhere/jwt/filter/CustomSuccessHandler.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index 1df564d..22a5af7 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -43,7 +43,9 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo Collection authorities = authentication.getAuthorities(); Iterator iterator = authorities.iterator(); GrantedAuthority auth = iterator.next(); - logger.info("Role: {}", auth.getAuthority()); + logger.debug("------------------------"); + logger.info("auth.getAuthority(): {}", auth.getAuthority()); + logger.debug("------------------------"); Role role = Role.valueOf(auth.getAuthority()); logger.debug("------------------------"); From 82cfc4cc4df992610fd282d39f56dbbfa9cae12a Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 05:55:19 +0900 Subject: [PATCH 15/51] =?UTF-8?q?fix=20:=20Authority()=20=EC=97=90?= =?UTF-8?q?=EB=9F=AC=20=ED=99=95=EC=9D=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/book_everywhere/auth/dto/CustomOAuth2User.java | 2 ++ .../auth/service/CustomOAuth2UserService.java | 3 +-- .../book_everywhere/jwt/filter/CustomSuccessHandler.java | 7 ------- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java b/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java index 1e7c5c8..844750d 100644 --- a/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java +++ b/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java @@ -1,5 +1,6 @@ package com.book_everywhere.auth.dto; +import com.book_everywhere.auth.entity.Role; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.user.OAuth2User; @@ -42,4 +43,5 @@ public String getName() { } + } diff --git a/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java b/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java index 113849e..5a76732 100644 --- a/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java +++ b/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java @@ -51,8 +51,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic httpSession.setAttribute("user", user); UserDto userDto = new UserDto(); userDto.setNickname(user.getNickname()); - userDto.setRole(userDto.getRole()); - + userDto.setRole(user.getRole()); return new CustomOAuth2User(userDto); } diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index 22a5af7..66d1f28 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -43,15 +43,8 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo Collection authorities = authentication.getAuthorities(); Iterator iterator = authorities.iterator(); GrantedAuthority auth = iterator.next(); - logger.debug("------------------------"); - logger.info("auth.getAuthority(): {}", auth.getAuthority()); - logger.debug("------------------------"); Role role = Role.valueOf(auth.getAuthority()); - logger.debug("------------------------"); - logger.debug("Role: {}", role); - logger.debug("------------------------"); - String access = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); String refresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); From eeef14c4d3d029691c7fc60bf0f2fb4629fd235d Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 06:20:58 +0900 Subject: [PATCH 16/51] =?UTF-8?q?fix=20:=20=EC=BF=A0=ED=82=A4=20=EC=9C=A0?= =?UTF-8?q?=ED=9A=A8=EA=B0=92=20=EB=B2=94=EC=9C=84=20=EC=A1=B0=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../book_everywhere/jwt/filter/CustomSuccessHandler.java | 1 - .../java/com/book_everywhere/jwt/token/JwtProvider.java | 9 ++------- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index 66d1f28..63f8769 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -28,7 +28,6 @@ @Component public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { - private static final Logger logger = LoggerFactory.getLogger(CustomSuccessHandler.class); private final JwtProvider jwtProvider; private final RefreshService refreshService; diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index 6287777..7250938 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -42,7 +42,7 @@ public Boolean isExpired(String token) { } public String createJwt(String category, String username, Role role, Long expiredMs) { - String jwt = Jwts.builder() + return Jwts.builder() .claim("category", category) .claim("username", username) .claim("role", role.toString()) @@ -50,11 +50,6 @@ public String createJwt(String category, String username, Role role, Long expire .expiration(new Date(System.currentTimeMillis() + expiredMs)) .signWith(secretKey) .compact(); - - // 생성된 JWT를 로그에 출력 - System.out.println("Created JWT: " + jwt); - - return jwt; } public Cookie createCookie(String key, String value) { @@ -62,7 +57,7 @@ public Cookie createCookie(String key, String value) { Cookie cookie = new Cookie(key, value); cookie.setMaxAge(24 * 60 * 60); //cookie.setSecure(true); -// cookie.setPath("/"); + cookie.setPath("/"); cookie.setHttpOnly(true); return cookie; From 8704c827c876b0c18d921b49e0ca0055a69a5841 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 06:58:10 +0900 Subject: [PATCH 17/51] =?UTF-8?q?fix=20:=20=EB=B6=88=ED=95=84=EC=9A=94?= =?UTF-8?q?=ED=95=9C=20redirect=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/book_everywhere/jwt/filter/CustomSuccessHandler.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index 63f8769..c3c1dd5 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -53,7 +53,6 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo // response.sendRedirect("http://localhost:3000/"); response.setHeader(ACCESS.getType(), access); response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); - response.sendRedirect("https://www.bookeverywhere.site/"); response.setStatus(HttpStatus.OK.value()); } From ef8032ab3ae700eb7381360e06a4c0174e16cbaa Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 07:04:40 +0900 Subject: [PATCH 18/51] =?UTF-8?q?fix=20:=20redirect=20=EC=9C=84=EC=B9=98?= =?UTF-8?q?=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/book_everywhere/auth/config/SecurityConfig.java | 1 + .../com/book_everywhere/jwt/filter/CustomSuccessHandler.java | 2 ++ 2 files changed, 3 insertions(+) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 041a284..c4802da 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -79,6 +79,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig.userService(customOAuth2UserService)) .successHandler(customSuccessHandler) + ) .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) ; diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index c3c1dd5..cea104c 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -51,6 +51,8 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo // response.addCookie(jwtProvider.createCookie("Authorization", refresh)); // response.sendRedirect("http://localhost:3000/"); + + response.sendRedirect("https://www.bookeverywhere.site/"); response.setHeader(ACCESS.getType(), access); response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); response.setStatus(HttpStatus.OK.value()); From 87628f710189bdaea0609d94df3f4fb9cdae4377 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 16:30:04 +0900 Subject: [PATCH 19/51] =?UTF-8?q?fix=20:=20=EC=BF=A0=ED=82=A4=20=EC=9D=B4?= =?UTF-8?q?=EB=A6=84=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/book_everywhere/jwt/filter/CustomSuccessHandler.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index cea104c..955c709 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -49,12 +49,13 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo refreshService.리프레시토큰생성(new RefreshDto(username, refresh, REFRESH.getExpirationTime())); -// response.addCookie(jwtProvider.createCookie("Authorization", refresh)); + // response.sendRedirect("http://localhost:3000/"); response.sendRedirect("https://www.bookeverywhere.site/"); response.setHeader(ACCESS.getType(), access); - response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); + response.addCookie(jwtProvider.createCookie("Authorization", refresh)); +// response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); response.setStatus(HttpStatus.OK.value()); } From 63cdf3c1c0e272ee1057f85f4da3d6790b4d4246 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 16:43:18 +0900 Subject: [PATCH 20/51] =?UTF-8?q?fix=20:=20=EB=A6=AC=EB=8B=A4=EC=9D=B4?= =?UTF-8?q?=EB=A0=89=EC=85=98=20=ED=85=8C=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/book_everywhere/jwt/filter/CustomSuccessHandler.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index 955c709..c574748 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -50,9 +50,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo refreshService.리프레시토큰생성(new RefreshDto(username, refresh, REFRESH.getExpirationTime())); -// response.sendRedirect("http://localhost:3000/"); - - response.sendRedirect("https://www.bookeverywhere.site/"); +// response.sendRedirect("https://www.bookeverywhere.site/"); response.setHeader(ACCESS.getType(), access); response.addCookie(jwtProvider.createCookie("Authorization", refresh)); // response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); From 925badad7788033a5fff6b0a2e48a9aa16556685 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 17:02:48 +0900 Subject: [PATCH 21/51] =?UTF-8?q?fix=20:=20JWT=20=ED=95=84=ED=84=B0=20?= =?UTF-8?q?=ED=85=8C=EC=8A=A4=ED=8A=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jwt/filter/CustomSuccessHandler.java | 4 +- .../book_everywhere/jwt/filter/JwtFilter.java | 64 +++++++++++++++++-- .../jwt/token/JwtProvider.java | 3 +- 3 files changed, 63 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index c574748..955c709 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -50,7 +50,9 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo refreshService.리프레시토큰생성(new RefreshDto(username, refresh, REFRESH.getExpirationTime())); -// response.sendRedirect("https://www.bookeverywhere.site/"); +// response.sendRedirect("http://localhost:3000/"); + + response.sendRedirect("https://www.bookeverywhere.site/"); response.setHeader(ACCESS.getType(), access); response.addCookie(jwtProvider.createCookie("Authorization", refresh)); // response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index 4320131..11e8a26 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -6,9 +6,12 @@ import com.book_everywhere.jwt.token.JwtProvider; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; +import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; @@ -23,25 +26,76 @@ public class JwtFilter extends OncePerRequestFilter { private final JwtProvider jwtProvider; + private final Logger logger = LoggerFactory.getLogger(JwtFilter.class); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - String accessToken = request.getHeader(ACCESS.getType()); + //여기서 엑세스를 받아야함 +// String accessToken = request.getHeader(ACCESS.getType()); +// +// if (accessToken == null) { +// filterChain.doFilter(request, response); +// return; +// } +// +// if (!validateToken(response, accessToken)) { +// return; +// } +// +// //토큰에서 username과 role 획득 +// UserDto userDto = new UserDto(); +// userDto.setNickname(jwtProvider.getUsername(accessToken)); +// userDto.setRole(jwtProvider.getRole(accessToken)); - if (accessToken == null) { + //cookie들을 불러온 뒤 Authorization Key에 담긴 쿠키를 찾음 + String authorization = null; + Cookie[] cookies = request.getCookies(); + for (Cookie cookie : cookies) { + + System.out.println(cookie.getName()); + if (cookie.getName().equals("Authorization")) { + + authorization = cookie.getValue(); + } + } + + //Authorization 헤더 검증 + if (authorization == null) { + + System.out.println("token null"); filterChain.doFilter(request, response); + + //조건이 해당되면 메소드 종료 (필수) return; } - if (!validateToken(response, accessToken)) { + //토큰 + String token = authorization; + + //토큰 소멸 시간 검증 + if (jwtProvider.isExpired(token)) { + + System.out.println("token expired"); + filterChain.doFilter(request, response); + + //조건이 해당되면 메소드 종료 (필수) return; } //토큰에서 username과 role 획득 + String username = jwtProvider.getUsername(token); + Role role = jwtProvider.getRole(token); + + //userDTO를 생성하여 값 set UserDto userDto = new UserDto(); - userDto.setNickname(jwtProvider.getUsername(accessToken)); - userDto.setRole(jwtProvider.getRole(accessToken)); + userDto.setNickname(username); + userDto.setRole(role); + + logger.info("JWT 필터 인증 절차 "); + logger.info("JWT 필터 인증 절차 "); + logger.info("이곳은 앞의 헤더를 인증하여 세션에 사용자를 등록해줍니다. "); + logger.info(String.valueOf(userDto)); //UserDetails에 회원 정보 객체 담기 CustomOAuth2User customOAuth2User = new CustomOAuth2User(userDto); diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index 7250938..4fa5090 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -53,9 +53,8 @@ public String createJwt(String category, String username, Role role, Long expire } public Cookie createCookie(String key, String value) { - Cookie cookie = new Cookie(key, value); - cookie.setMaxAge(24 * 60 * 60); + cookie.setMaxAge(60 * 60 * 60); //cookie.setSecure(true); cookie.setPath("/"); cookie.setHttpOnly(true); From a477c6b83f1779858736fde67fda842507104ea0 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 17:13:00 +0900 Subject: [PATCH 22/51] =?UTF-8?q?fix=20:=20JWT=20=ED=95=84=ED=84=B0?= =?UTF-8?q?=EC=B2=B4=EC=9D=B8=20=EC=88=9C=EC=84=9C=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/book_everywhere/auth/config/SecurityConfig.java | 2 +- src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index c4802da..a372293 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -63,7 +63,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .csrf(AbstractHttpConfigurer::disable) .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) - .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) + .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() // 테스트 관련 url diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index 11e8a26..80168ba 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -30,8 +30,9 @@ public class JwtFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - //여기서 엑세스를 받아야함 + + // String accessToken = request.getHeader(ACCESS.getType()); // // if (accessToken == null) { From aac32b8f3a21b683a6946eff3e189ba0baea831b Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 17:26:32 +0900 Subject: [PATCH 23/51] =?UTF-8?q?fix=20:=20=EB=B3=B5=EC=9E=A1=ED=95=9C=20?= =?UTF-8?q?=ED=98=95=EB=B3=80=ED=99=98=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../book_everywhere/jwt/filter/JwtFilter.java | 36 +++++++++---------- .../jwt/token/JwtProvider.java | 3 +- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index 80168ba..64533e5 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -30,25 +30,7 @@ public class JwtFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - //여기서 엑세스를 받아야함 - - -// String accessToken = request.getHeader(ACCESS.getType()); -// -// if (accessToken == null) { -// filterChain.doFilter(request, response); -// return; -// } -// -// if (!validateToken(response, accessToken)) { -// return; -// } -// -// //토큰에서 username과 role 획득 -// UserDto userDto = new UserDto(); -// userDto.setNickname(jwtProvider.getUsername(accessToken)); -// userDto.setRole(jwtProvider.getRole(accessToken)); - + //여기서 나중에 front에서 엑세스토큰을 받아야함 //cookie들을 불러온 뒤 Authorization Key에 담긴 쿠키를 찾음 String authorization = null; Cookie[] cookies = request.getCookies(); @@ -88,6 +70,22 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse String username = jwtProvider.getUsername(token); Role role = jwtProvider.getRole(token); +// String accessToken = request.getHeader(ACCESS.getType()); +// +// if (accessToken == null) { +// filterChain.doFilter(request, response); +// return; +// } +// +// if (!validateToken(response, accessToken)) { +// return; +// } +// +// //토큰에서 username과 role 획득 +// UserDto userDto = new UserDto(); +// userDto.setNickname(jwtProvider.getUsername(accessToken)); +// userDto.setRole(jwtProvider.getRole(accessToken)); + //userDTO를 생성하여 값 set UserDto userDto = new UserDto(); userDto.setNickname(username); diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index 4fa5090..dfb07b6 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -30,7 +30,8 @@ public String getUsername(String token) { } public Role getRole(String token) { - return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", Role.class); + String role = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); + return Role.valueOf(role); } public String getCategory(String token) { From 52f680be7cddd4724c4f7eeefcc3dfefaa05b2b4 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 17:27:40 +0900 Subject: [PATCH 24/51] =?UTF-8?q?fix=20:=20=EB=B3=B5=EC=9E=A1=ED=95=9C=20?= =?UTF-8?q?=ED=98=95=EB=B3=80=ED=99=98=20=EC=A0=9C=EA=B1=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/book_everywhere/jwt/filter/JwtFilter.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index 64533e5..fc3edab 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -43,6 +43,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse } } + + //Authorization 헤더 검증 if (authorization == null) { @@ -55,7 +57,10 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse //토큰 String token = authorization; - + System.out.println("@@@@@@@@@@@@@@@@@@@@@@"); + System.out.println(token); + System.out.println(jwtProvider.getRole(token)); + System.out.println("@@@@@@@@@@@@@@@@@@@@@@"); //토큰 소멸 시간 검증 if (jwtProvider.isExpired(token)) { From 28fe3faa69a217c677ab0fcc9ac17b90c2d242c3 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 18:05:14 +0900 Subject: [PATCH 25/51] =?UTF-8?q?fix=20:=20refresh=20=EA=B8=B0=EB=8A=A5=20?= =?UTF-8?q?=EB=B6=80=EB=B6=84=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/config/SecurityConfig.java | 3 +- .../auth/dto/CustomOAuth2User.java | 2 +- .../com/book_everywhere/auth/dto/UserDto.java | 4 +-- .../auth/service/CustomOAuth2UserService.java | 2 +- .../jwt/controller/RefreshController.java | 20 ++++++------ .../jwt/filter/CustomSuccessHandler.java | 18 +++++------ .../book_everywhere/jwt/filter/JwtFilter.java | 31 ++++++------------- .../jwt/token/JwtProvider.java | 11 +++---- 8 files changed, 38 insertions(+), 53 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index a372293..027f6d3 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -64,6 +64,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) +// .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() // 테스트 관련 url @@ -81,7 +82,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .successHandler(customSuccessHandler) ) - .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) + ; return http.build(); } diff --git a/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java b/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java index 844750d..d58894a 100644 --- a/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java +++ b/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java @@ -29,7 +29,7 @@ public Collection getAuthorities() { collection.add(new GrantedAuthority() { @Override public String getAuthority() { - return String.valueOf(userDto.getRole()); + return userDto.getRole(); } }); diff --git a/src/main/java/com/book_everywhere/auth/dto/UserDto.java b/src/main/java/com/book_everywhere/auth/dto/UserDto.java index 8fab3cf..0a9c152 100644 --- a/src/main/java/com/book_everywhere/auth/dto/UserDto.java +++ b/src/main/java/com/book_everywhere/auth/dto/UserDto.java @@ -1,10 +1,10 @@ package com.book_everywhere.auth.dto; -import com.book_everywhere.auth.entity.Role; + import lombok.Data; @Data public class UserDto { private String nickname; - private Role role; + private String role; } diff --git a/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java b/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java index 5a76732..f06a525 100644 --- a/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java +++ b/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java @@ -51,7 +51,7 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic httpSession.setAttribute("user", user); UserDto userDto = new UserDto(); userDto.setNickname(user.getNickname()); - userDto.setRole(user.getRole()); + userDto.setRole(String.valueOf(user.getRole())); return new CustomOAuth2User(userDto); } diff --git a/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java b/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java index 28bf94b..a272d15 100644 --- a/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java +++ b/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java @@ -66,18 +66,18 @@ public CMRespDto reissue(HttpServletRequest request, HttpServletResponse resp String username = jwtProvider.getUsername(refresh); - Role role = jwtProvider.getRole(refresh); + String role = jwtProvider.getRole(refresh); //make new JWT - String newAccess = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); - String newRefresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); - - refreshService.리프레시토큰삭제(refresh); - refreshService.리프레시토큰생성(new RefreshDto(username, newRefresh, REFRESH.getExpirationTime())); - - //response - response.setHeader(ACCESS.getType(), newAccess); - response.addCookie(jwtProvider.createCookie(REFRESH.getType(), newRefresh)); +// String newAccess = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); +// String newRefresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); +// +// refreshService.리프레시토큰삭제(refresh); +// refreshService.리프레시토큰생성(new RefreshDto(username, newRefresh, REFRESH.getExpirationTime())); +// +// //response +// response.setHeader(ACCESS.getType(), newAccess); +// response.addCookie(jwtProvider.createCookie(REFRESH.getType(), newRefresh)); return new CMRespDto<>(HttpStatus.OK, null, "재발급 완료"); } diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index 955c709..d745313 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -42,20 +42,18 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo Collection authorities = authentication.getAuthorities(); Iterator iterator = authorities.iterator(); GrantedAuthority auth = iterator.next(); - Role role = Role.valueOf(auth.getAuthority()); + String role = auth.getAuthority(); - String access = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); - String refresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); +// String access = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); +// String refresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); + String token = jwtProvider.createJwt(username, role, REFRESH.getExpirationTime()); +// refreshService.리프레시토큰생성(new RefreshDto(username, refresh, REFRESH.getExpirationTime())); - refreshService.리프레시토큰생성(new RefreshDto(username, refresh, REFRESH.getExpirationTime())); - -// response.sendRedirect("http://localhost:3000/"); - - response.sendRedirect("https://www.bookeverywhere.site/"); - response.setHeader(ACCESS.getType(), access); - response.addCookie(jwtProvider.createCookie("Authorization", refresh)); +// response.setHeader(ACCESS.getType(), access); // response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); + response.addCookie(jwtProvider.createCookie("Authorization", token)); + response.sendRedirect("https://www.bookeverywhere.site/"); response.setStatus(HttpStatus.OK.value()); } diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index fc3edab..3286673 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -30,21 +30,16 @@ public class JwtFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - //여기서 나중에 front에서 엑세스토큰을 받아야함 - //cookie들을 불러온 뒤 Authorization Key에 담긴 쿠키를 찾음 String authorization = null; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { - System.out.println(cookie.getName()); if (cookie.getName().equals("Authorization")) { authorization = cookie.getValue(); } } - - //Authorization 헤더 검증 if (authorization == null) { @@ -57,11 +52,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse //토큰 String token = authorization; - System.out.println("@@@@@@@@@@@@@@@@@@@@@@"); - System.out.println(token); - System.out.println(jwtProvider.getRole(token)); - System.out.println("@@@@@@@@@@@@@@@@@@@@@@"); - //토큰 소멸 시간 검증 + if (jwtProvider.isExpired(token)) { System.out.println("token expired"); @@ -73,9 +64,15 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse //토큰에서 username과 role 획득 String username = jwtProvider.getUsername(token); - Role role = jwtProvider.getRole(token); + String role = jwtProvider.getRole(token); + + //userDTO를 생성하여 값 set + UserDto userDto = new UserDto(); + userDto.setNickname(username); + userDto.setRole(role); -// String accessToken = request.getHeader(ACCESS.getType()); + + // String accessToken = request.getHeader(ACCESS.getType()); // // if (accessToken == null) { // filterChain.doFilter(request, response); @@ -91,16 +88,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse // userDto.setNickname(jwtProvider.getUsername(accessToken)); // userDto.setRole(jwtProvider.getRole(accessToken)); - //userDTO를 생성하여 값 set - UserDto userDto = new UserDto(); - userDto.setNickname(username); - userDto.setRole(role); - - logger.info("JWT 필터 인증 절차 "); - logger.info("JWT 필터 인증 절차 "); - logger.info("이곳은 앞의 헤더를 인증하여 세션에 사용자를 등록해줍니다. "); - logger.info(String.valueOf(userDto)); - //UserDetails에 회원 정보 객체 담기 CustomOAuth2User customOAuth2User = new CustomOAuth2User(userDto); diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index dfb07b6..f6ff3da 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -29,9 +29,8 @@ public String getUsername(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("username", String.class); } - public Role getRole(String token) { - String role = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); - return Role.valueOf(role); + public String getRole(String token) { + return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); } public String getCategory(String token) { @@ -42,11 +41,11 @@ public Boolean isExpired(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date()); } - public String createJwt(String category, String username, Role role, Long expiredMs) { + public String createJwt( String username, String role, Long expiredMs) { return Jwts.builder() - .claim("category", category) +// .claim("category", category) .claim("username", username) - .claim("role", role.toString()) + .claim("role", role) .issuedAt(new Date(System.currentTimeMillis())) .expiration(new Date(System.currentTimeMillis() + expiredMs)) .signWith(secretKey) From 3385bdfe8bcd2d53524bc6613b2f0d10cb23bd44 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 18:18:20 +0900 Subject: [PATCH 26/51] =?UTF-8?q?fix=20:=20refresh=20=EA=B8=B0=EB=8A=A5=20?= =?UTF-8?q?=EB=B6=80=EB=B6=84=20=EC=82=AD=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index 3286673..fcd490a 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -2,7 +2,6 @@ import com.book_everywhere.auth.dto.CustomOAuth2User; import com.book_everywhere.auth.dto.UserDto; -import com.book_everywhere.auth.entity.Role; import com.book_everywhere.jwt.token.JwtProvider; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -10,8 +9,6 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; @@ -26,10 +23,10 @@ public class JwtFilter extends OncePerRequestFilter { private final JwtProvider jwtProvider; - private final Logger logger = LoggerFactory.getLogger(JwtFilter.class); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + String authorization = null; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { From 77256b26e311029925750b427fd2215f4b52b267 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 18:23:11 +0900 Subject: [PATCH 27/51] =?UTF-8?q?fix=20:=20=EC=8B=9C=ED=81=90=EB=A6=AC?= =?UTF-8?q?=ED=8B=B0=20=ED=95=84=ED=84=B0=EC=B2=B4=EC=9D=B8=20=EC=9C=84?= =?UTF-8?q?=EC=B9=98=EC=A1=B0=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../book_everywhere/auth/config/SecurityConfig.java | 3 ++- .../com/book_everywhere/jwt/filter/JwtFilter.java | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 027f6d3..cf9d1aa 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -63,7 +63,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .csrf(AbstractHttpConfigurer::disable) .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) - .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) +// .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) + .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) // .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index fcd490a..1c187cc 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -26,7 +26,18 @@ public class JwtFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { + String requestUri = request.getRequestURI(); + if (requestUri.matches("^\\/login(?:\\/.*)?$")) { + + filterChain.doFilter(request, response); + return; + } + if (requestUri.matches("^\\/oauth2(?:\\/.*)?$")) { + + filterChain.doFilter(request, response); + return; + } String authorization = null; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { From 1f1d5b869e91c5e17176d1e37898de340a02c7ba Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 18:40:55 +0900 Subject: [PATCH 28/51] =?UTF-8?q?fix=20:=20refresh=20token=20=EC=A1=B0?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/config/SecurityConfig.java | 12 ++-- .../jwt/controller/RefreshController.java | 18 ++--- .../jwt/filter/CustomSuccessHandler.java | 14 ++-- .../book_everywhere/jwt/filter/JwtFilter.java | 65 ++----------------- .../jwt/token/JwtProvider.java | 4 +- 5 files changed, 28 insertions(+), 85 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index cf9d1aa..3aae19e 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -44,7 +44,7 @@ public BCryptPasswordEncoder encoder() { public CorsConfigurationSource corsConfigurationSource() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); - config.setAllowedOriginPatterns(Arrays.asList("https://*.bookeverywhere.site","http://localhost:3000")); + config.setAllowedOriginPatterns(Arrays.asList("https://*.bookeverywhere.site", "http://localhost:3000")); config.setAllowCredentials(true); // 크리덴셜 허용 config.addAllowedHeader("*"); config.addAllowedMethod("*"); @@ -63,15 +63,15 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .csrf(AbstractHttpConfigurer::disable) .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) -// .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) - .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) -// .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) + .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) +// .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) + .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() // 테스트 관련 url - .requestMatchers("/health","/env","/test/**","/swagger-ui/**").permitAll() + .requestMatchers("/health", "/env", "/test/**", "/swagger-ui/**").permitAll() // 비회원도 볼수있는 url - .requestMatchers("/api/review","/api/map","/api/tags","/api/data/**").permitAll() + .requestMatchers("/api/review", "/api/map", "/api/tags", "/api/data/**").permitAll() // 나머지 .requestMatchers("/api/**").hasAuthority("ROLE_MEMBER") .anyRequest().authenticated() diff --git a/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java b/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java index a272d15..8987dcf 100644 --- a/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java +++ b/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java @@ -69,15 +69,15 @@ public CMRespDto reissue(HttpServletRequest request, HttpServletResponse resp String role = jwtProvider.getRole(refresh); //make new JWT -// String newAccess = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); -// String newRefresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); -// -// refreshService.리프레시토큰삭제(refresh); -// refreshService.리프레시토큰생성(new RefreshDto(username, newRefresh, REFRESH.getExpirationTime())); -// -// //response -// response.setHeader(ACCESS.getType(), newAccess); -// response.addCookie(jwtProvider.createCookie(REFRESH.getType(), newRefresh)); + String newAccess = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); + String newRefresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); + + refreshService.리프레시토큰삭제(refresh); + refreshService.리프레시토큰생성(new RefreshDto(username, newRefresh, REFRESH.getExpirationTime())); + + //response + response.setHeader(ACCESS.getType(), newAccess); + response.addCookie(jwtProvider.createCookie(REFRESH.getType(), newRefresh)); return new CMRespDto<>(HttpStatus.OK, null, "재발급 완료"); } diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index d745313..2d6be5f 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -33,7 +33,6 @@ public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { - //OAuth2User CustomOAuth2User customUserDetails = (CustomOAuth2User) authentication.getPrincipal(); @@ -44,17 +43,14 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo GrantedAuthority auth = iterator.next(); String role = auth.getAuthority(); -// String access = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); -// String refresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); - String token = jwtProvider.createJwt(username, role, REFRESH.getExpirationTime()); -// refreshService.리프레시토큰생성(new RefreshDto(username, refresh, REFRESH.getExpirationTime())); + String access = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); + String refresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); + refreshService.리프레시토큰생성(new RefreshDto(username, refresh, REFRESH.getExpirationTime())); -// response.setHeader(ACCESS.getType(), access); -// response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); - response.addCookie(jwtProvider.createCookie("Authorization", token)); + response.setHeader(ACCESS.getType(), access); + response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); response.sendRedirect("https://www.bookeverywhere.site/"); - response.setStatus(HttpStatus.OK.value()); } } diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index 1c187cc..cd5bda5 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -26,75 +26,22 @@ public class JwtFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - String requestUri = request.getRequestURI(); + //여기서 헤더가 access인 + String accessToken = request.getHeader(ACCESS.getType()); - if (requestUri.matches("^\\/login(?:\\/.*)?$")) { - - filterChain.doFilter(request, response); - return; - } - if (requestUri.matches("^\\/oauth2(?:\\/.*)?$")) { - - filterChain.doFilter(request, response); - return; - } - String authorization = null; - Cookie[] cookies = request.getCookies(); - for (Cookie cookie : cookies) { - - if (cookie.getName().equals("Authorization")) { - - authorization = cookie.getValue(); - } - } - - //Authorization 헤더 검증 - if (authorization == null) { - - System.out.println("token null"); + if (accessToken == null) { filterChain.doFilter(request, response); - - //조건이 해당되면 메소드 종료 (필수) return; } - //토큰 - String token = authorization; - - if (jwtProvider.isExpired(token)) { - - System.out.println("token expired"); - filterChain.doFilter(request, response); - - //조건이 해당되면 메소드 종료 (필수) + if (!validateToken(response, accessToken)) { return; } //토큰에서 username과 role 획득 - String username = jwtProvider.getUsername(token); - String role = jwtProvider.getRole(token); - - //userDTO를 생성하여 값 set UserDto userDto = new UserDto(); - userDto.setNickname(username); - userDto.setRole(role); - - - // String accessToken = request.getHeader(ACCESS.getType()); -// -// if (accessToken == null) { -// filterChain.doFilter(request, response); -// return; -// } -// -// if (!validateToken(response, accessToken)) { -// return; -// } -// -// //토큰에서 username과 role 획득 -// UserDto userDto = new UserDto(); -// userDto.setNickname(jwtProvider.getUsername(accessToken)); -// userDto.setRole(jwtProvider.getRole(accessToken)); + userDto.setNickname(jwtProvider.getUsername(accessToken)); + userDto.setRole(jwtProvider.getRole(accessToken)); //UserDetails에 회원 정보 객체 담기 CustomOAuth2User customOAuth2User = new CustomOAuth2User(userDto); diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index f6ff3da..152515a 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -41,9 +41,9 @@ public Boolean isExpired(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date()); } - public String createJwt( String username, String role, Long expiredMs) { + public String createJwt(String category, String username, String role, Long expiredMs) { return Jwts.builder() -// .claim("category", category) + .claim("category", category) .claim("username", username) .claim("role", role) .issuedAt(new Date(System.currentTimeMillis())) From 630ea3d54f35a1b84d8dd42f576499889e1aca49 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 23:06:30 +0900 Subject: [PATCH 29/51] =?UTF-8?q?fix=20:=20refresh=20token=20=EC=A1=B0?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/book_everywhere/auth/config/SecurityConfig.java | 2 ++ .../com/book_everywhere/jwt/filter/CustomSuccessHandler.java | 5 ++--- .../domain/jwt/service/RefreshServiceTest.java | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 3aae19e..9f7a3d6 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -81,6 +81,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig.userService(customOAuth2UserService)) .successHandler(customSuccessHandler) + .redirectionEndpoint(redirectionEndpointConfig -> + redirectionEndpointConfig.baseUri("https://www.bookeverywhere.site/oauth2/authorization/kakao")) ) diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index 2d6be5f..eeac601 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -47,10 +47,9 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo String refresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); refreshService.리프레시토큰생성(new RefreshDto(username, refresh, REFRESH.getExpirationTime())); - - response.setHeader(ACCESS.getType(), access); +// response.setHeader(ACCESS.getType(), access); + response.addCookie(jwtProvider.createCookie(ACCESS.getType(), access)); response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); response.sendRedirect("https://www.bookeverywhere.site/"); } - } diff --git a/src/test/java/com/book_everywhere/domain/jwt/service/RefreshServiceTest.java b/src/test/java/com/book_everywhere/domain/jwt/service/RefreshServiceTest.java index 7da9406..82f489e 100644 --- a/src/test/java/com/book_everywhere/domain/jwt/service/RefreshServiceTest.java +++ b/src/test/java/com/book_everywhere/domain/jwt/service/RefreshServiceTest.java @@ -27,7 +27,7 @@ public class RefreshServiceTest { @Test @DisplayName("Service_리프레시 토큰 생성 테스트") void 리프레시토큰생성_테스트() { - RefreshDto refreshDto = new RefreshDto("ID", "token", String.valueOf(1000L)); // 1000L은 토큰 만료 시간 + RefreshDto refreshDto = new RefreshDto("ID", "token",1000L); // 1000L은 토큰 만료 시간 given(refreshRepository.save(any())).willReturn(any()); // When @@ -55,7 +55,7 @@ public class RefreshServiceTest { @DisplayName("Service_리프레시 토큰 삭제 테스트") void 리프레시토큰삭제_테스트() { // Given - RefreshDto refreshDto = new RefreshDto("ID", "token", String.valueOf(1000L)); // 1000L은 토큰 만료 시간 + RefreshDto refreshDto = new RefreshDto("ID", "token", 1000L); // 1000L은 토큰 만료 시간 given(refreshRepository.save(any())).willReturn(any()); // When From 97f22f902ec90c7f4333bdcbd547e302a4f22a80 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 23:07:06 +0900 Subject: [PATCH 30/51] =?UTF-8?q?fix=20:=20refresh=20token=20=EC=A1=B0?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/book_everywhere/jwt/filter/CustomSuccessHandler.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index eeac601..10fef56 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -47,7 +47,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo String refresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); refreshService.리프레시토큰생성(new RefreshDto(username, refresh, REFRESH.getExpirationTime())); -// response.setHeader(ACCESS.getType(), access); + response.setHeader(ACCESS.getType(), access); response.addCookie(jwtProvider.createCookie(ACCESS.getType(), access)); response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); response.sendRedirect("https://www.bookeverywhere.site/"); From 74500ac4ffab7f714539cc2cf5177ed61c3ba510 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 23:12:29 +0900 Subject: [PATCH 31/51] =?UTF-8?q?fix=20:=20refresh=20token=20=EC=A1=B0?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/book_everywhere/auth/config/SecurityConfig.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 9f7a3d6..522f433 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -81,8 +81,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig.userService(customOAuth2UserService)) .successHandler(customSuccessHandler) - .redirectionEndpoint(redirectionEndpointConfig -> - redirectionEndpointConfig.baseUri("https://www.bookeverywhere.site/oauth2/authorization/kakao")) +// .redirectionEndpoint(redirectionEndpointConfig -> +// redirectionEndpointConfig.baseUri("https://www.bookeverywhere.site/oauth2/authorization/kakao")) ) From 1d17c62c178eb02b8a24b5f497cedfd03a71a5a2 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 1 Apr 2024 23:51:32 +0900 Subject: [PATCH 32/51] =?UTF-8?q?fix=20:=20access=20token=20=EC=BF=A0?= =?UTF-8?q?=ED=82=A4=EC=97=90=20=EB=8B=B4=EA=B8=B0=20=EC=8B=A4=ED=97=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../book_everywhere/auth/config/SecurityConfig.java | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 522f433..1ff0c1a 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -63,8 +63,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .csrf(AbstractHttpConfigurer::disable) .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) - .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) -// .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) +// .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) + .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() @@ -78,14 +78,13 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { ) .oauth2Login(oauth2Login -> oauth2Login + .successHandler(customSuccessHandler) .userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig.userService(customOAuth2UserService)) - .successHandler(customSuccessHandler) -// .redirectionEndpoint(redirectionEndpointConfig -> -// redirectionEndpointConfig.baseUri("https://www.bookeverywhere.site/oauth2/authorization/kakao")) + .redirectionEndpoint(redirectionEndpointConfig -> + redirectionEndpointConfig.baseUri("https://api.bookeverywhere.site/oauth2/authorization/kakao")) ) - ; return http.build(); } From ffb7f6e36259db98c1dac0c01a895a44666f5030 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 00:20:01 +0900 Subject: [PATCH 33/51] =?UTF-8?q?fix=20:=20access=20token=20=EC=BF=A0?= =?UTF-8?q?=ED=82=A4=EC=97=90=20=EB=8B=B4=EA=B8=B0=20=EC=8B=A4=ED=97=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/book_everywhere/auth/config/SecurityConfig.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 1ff0c1a..672fd56 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -63,8 +63,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .csrf(AbstractHttpConfigurer::disable) .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) -// .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) - .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) + .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) +// .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() @@ -81,8 +81,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .successHandler(customSuccessHandler) .userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig.userService(customOAuth2UserService)) - .redirectionEndpoint(redirectionEndpointConfig -> - redirectionEndpointConfig.baseUri("https://api.bookeverywhere.site/oauth2/authorization/kakao")) +// .redirectionEndpoint(redirectionEndpointConfig -> +// redirectionEndpointConfig.baseUri("https://api.bookeverywhere.site/oauth2/authorization/kakao" )) ) ; From 00505e45d446da4a1ab5b16f5c398add13d21d7c Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 00:34:38 +0900 Subject: [PATCH 34/51] =?UTF-8?q?fix=20:=20access=20token=20=EC=BF=A0?= =?UTF-8?q?=ED=82=A4=EC=97=90=20=EB=8B=B4=EA=B8=B0=20=EC=8B=A4=ED=97=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/book_everywhere/jwt/filter/JwtFilter.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index cd5bda5..e672709 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -27,7 +27,14 @@ public class JwtFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //여기서 헤더가 access인 - String accessToken = request.getHeader(ACCESS.getType()); + String accessToken = null; + Cookie[] cookies = request.getCookies(); + for (Cookie cookie : cookies) { + logger.info(cookies); + if (cookie.getName().equals("access")) { + accessToken = cookie.getValue(); + } + } if (accessToken == null) { filterChain.doFilter(request, response); From 4a607908062bba2b7b695644fb76444be12dd0d7 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 00:41:23 +0900 Subject: [PATCH 35/51] =?UTF-8?q?fix=20:=20access=20token=20=EC=BF=A0?= =?UTF-8?q?=ED=82=A4=EC=97=90=20=EB=8B=B4=EA=B8=B0=20=EC=8B=A4=ED=97=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/book_everywhere/jwt/token/JwtProvider.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index 152515a..e58214e 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -14,6 +14,7 @@ import java.nio.charset.StandardCharsets; import java.util.Date; +@RequiredArgsConstructor @Component public class JwtProvider { From d44339da888292da8fce1b3aba73bd4f0524095a Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 00:56:20 +0900 Subject: [PATCH 36/51] =?UTF-8?q?fix=20:=20=ED=95=84=ED=84=B0=EC=9C=84?= =?UTF-8?q?=EC=B9=98=20=EC=A1=B0=EC=A0=95=20=EB=8B=B4=EA=B8=B0=20=EC=8B=A4?= =?UTF-8?q?=ED=97=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/book_everywhere/auth/config/SecurityConfig.java | 5 +++-- src/main/java/com/book_everywhere/jwt/token/JwtProvider.java | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 672fd56..34a1077 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -16,6 +16,7 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.logout.LogoutFilter; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.CorsConfiguration; @@ -63,8 +64,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .csrf(AbstractHttpConfigurer::disable) .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) - .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) -// .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) + .addFilterAfter(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class) +// .addFilterBefore(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index e58214e..51c4978 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -55,7 +55,7 @@ public String createJwt(String category, String username, String role, Long expi public Cookie createCookie(String key, String value) { Cookie cookie = new Cookie(key, value); - cookie.setMaxAge(60 * 60 * 60); + cookie.setMaxAge(60 * 60 * 60 * 60); //cookie.setSecure(true); cookie.setPath("/"); cookie.setHttpOnly(true); From 751fbcb98696bc9a467395a557cea6de9c06699f Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 01:02:45 +0900 Subject: [PATCH 37/51] =?UTF-8?q?fix=20:=20=ED=95=84=ED=84=B0=EC=9C=84?= =?UTF-8?q?=EC=B9=98=20=EC=A1=B0=EC=A0=95=20=EB=8B=B4=EA=B8=B0=20=EC=8B=A4?= =?UTF-8?q?=ED=97=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/book_everywhere/auth/config/SecurityConfig.java | 2 +- src/main/java/com/book_everywhere/jwt/token/JwtProvider.java | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 34a1077..4025cbc 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -65,7 +65,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) .addFilterAfter(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class) -// .addFilterBefore(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class) +// .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index 51c4978..6a4fe21 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -14,7 +14,6 @@ import java.nio.charset.StandardCharsets; import java.util.Date; -@RequiredArgsConstructor @Component public class JwtProvider { From ca2c6ec96553b848d8dd4d8748583aeaa45ad00f Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 01:21:10 +0900 Subject: [PATCH 38/51] =?UTF-8?q?fix=20:=20=ED=95=84=ED=84=B0=EC=9C=84?= =?UTF-8?q?=EC=B9=98=20=EC=A1=B0=EC=A0=95=20=EB=8B=B4=EA=B8=B0=20=EC=8B=A4?= =?UTF-8?q?=ED=97=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/book_everywhere/auth/config/SecurityConfig.java | 2 +- .../java/com/book_everywhere/jwt/filter/JwtFilter.java | 8 ++++++-- .../java/com/book_everywhere/jwt/token/JwtProvider.java | 2 -- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 4025cbc..a06c885 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -79,9 +79,9 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { ) .oauth2Login(oauth2Login -> oauth2Login - .successHandler(customSuccessHandler) .userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig.userService(customOAuth2UserService)) + .successHandler(customSuccessHandler) // .redirectionEndpoint(redirectionEndpointConfig -> // redirectionEndpointConfig.baseUri("https://api.bookeverywhere.site/oauth2/authorization/kakao" )) diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index e672709..7f55442 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -30,8 +30,12 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse String accessToken = null; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { - logger.info(cookies); - if (cookie.getName().equals("access")) { + logger.info("@@@@@@@@@@@@@@@@@@@@@@"); + logger.info("@@@@@@@@@@@@@@@@@@@@@@"); + logger.info("@@@@@@@@@@@@@@@@@@@@@@"); + logger.info("@@@@@@@@@@@@@@@@@@@@@@"); + logger.info(cookie); + if (cookie.getName().equals(ACCESS.getType())) { accessToken = cookie.getValue(); } } diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index 6a4fe21..d2735bd 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -1,9 +1,7 @@ package com.book_everywhere.jwt.token; -import com.book_everywhere.auth.entity.Role; import io.jsonwebtoken.*; import jakarta.servlet.http.Cookie; -import lombok.RequiredArgsConstructor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; From 2beebb982b03ed48982137044bf42698fdf056ff Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 01:24:59 +0900 Subject: [PATCH 39/51] =?UTF-8?q?fix=20:=EC=BF=A0=ED=82=A4=EC=98=88?= =?UTF-8?q?=EC=99=B8=EC=B2=98=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/book_everywhere/jwt/filter/JwtFilter.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index 7f55442..dc8e822 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -29,6 +29,16 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse //여기서 헤더가 access인 String accessToken = null; Cookie[] cookies = request.getCookies(); + if (cookies == null) { + // 쿠키가 없음을 처리하는 로직 + logger.info("@@@@@@@@@@@@@@@@@@@@@@"); + logger.info("@@@@@@@@@@@@@@@@@@@@@@"); + logger.info("@@@@@@@@@@@@@@@@@@@@@@"); + logger.info("@@@@@@@@@@@@@@@@@@@@@@"); + logger.info("쿠키없다는데? 왜없냐 ㄹㅇ"); + filterChain.doFilter(request, response); + return; + } for (Cookie cookie : cookies) { logger.info("@@@@@@@@@@@@@@@@@@@@@@"); logger.info("@@@@@@@@@@@@@@@@@@@@@@"); From 543fb17ff1f18a00a1072da49d0a99205ff0f468 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 01:38:43 +0900 Subject: [PATCH 40/51] =?UTF-8?q?fix=20:=EC=BF=A0=ED=82=A4=EC=98=88?= =?UTF-8?q?=EC=99=B8=EC=B2=98=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../jwt/filter/CustomSuccessHandler.java | 1 + .../book_everywhere/jwt/filter/JwtFilter.java | 43 ++++++++++--------- .../jwt/token/JwtProvider.java | 2 +- 3 files changed, 25 insertions(+), 21 deletions(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index 10fef56..008ae05 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -51,5 +51,6 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo response.addCookie(jwtProvider.createCookie(ACCESS.getType(), access)); response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); response.sendRedirect("https://www.bookeverywhere.site/"); + response.setStatus(HttpStatus.OK.value()); } } diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index dc8e822..c31dbee 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -27,28 +27,31 @@ public class JwtFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //여기서 헤더가 access인 - String accessToken = null; - Cookie[] cookies = request.getCookies(); - if (cookies == null) { - // 쿠키가 없음을 처리하는 로직 - logger.info("@@@@@@@@@@@@@@@@@@@@@@"); - logger.info("@@@@@@@@@@@@@@@@@@@@@@"); - logger.info("@@@@@@@@@@@@@@@@@@@@@@"); - logger.info("@@@@@@@@@@@@@@@@@@@@@@"); - logger.info("쿠키없다는데? 왜없냐 ㄹㅇ"); - filterChain.doFilter(request, response); - return; - } - for (Cookie cookie : cookies) { - logger.info("@@@@@@@@@@@@@@@@@@@@@@"); - logger.info("@@@@@@@@@@@@@@@@@@@@@@"); + String accessToken = request.getHeader(ACCESS.getType()); + + +// String accessToken = null; +// Cookie[] cookies = request.getCookies(); +// if (cookies == null) { +// // 쿠키가 없음을 처리하는 로직 +// logger.info("@@@@@@@@@@@@@@@@@@@@@@"); logger.info("@@@@@@@@@@@@@@@@@@@@@@"); logger.info("@@@@@@@@@@@@@@@@@@@@@@"); - logger.info(cookie); - if (cookie.getName().equals(ACCESS.getType())) { - accessToken = cookie.getValue(); - } - } + logger.info(accessToken); +// logger.info("쿠키없다는데? 왜없냐 ㄹㅇ"); +// filterChain.doFilter(request, response); +// return; +// } +// for (Cookie cookie : cookies) { +// logger.info("@@@@@@@@@@@@@@@@@@@@@@"); +// logger.info("@@@@@@@@@@@@@@@@@@@@@@"); +// logger.info("@@@@@@@@@@@@@@@@@@@@@@"); +// logger.info("@@@@@@@@@@@@@@@@@@@@@@"); +// logger.info(cookie); +// if (cookie.getName().equals(ACCESS.getType())) { +// accessToken = cookie.getValue(); +// } +// } if (accessToken == null) { filterChain.doFilter(request, response); diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index d2735bd..d9afa81 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -52,7 +52,7 @@ public String createJwt(String category, String username, String role, Long expi public Cookie createCookie(String key, String value) { Cookie cookie = new Cookie(key, value); - cookie.setMaxAge(60 * 60 * 60 * 60); + cookie.setMaxAge(24 * 60 * 60); //cookie.setSecure(true); cookie.setPath("/"); cookie.setHttpOnly(true); From f180a43c37ce4653916d750acbba612634187a92 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 01:50:51 +0900 Subject: [PATCH 41/51] fix : access header --- src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index c31dbee..c194bb5 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -28,7 +28,7 @@ public class JwtFilter extends OncePerRequestFilter { protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //여기서 헤더가 access인 String accessToken = request.getHeader(ACCESS.getType()); - + logger.info(request); // String accessToken = null; // Cookie[] cookies = request.getCookies(); From 34bc4a4270bb238c374ecec8d06cfc25c8464736 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 01:59:23 +0900 Subject: [PATCH 42/51] fix : access header --- .../book_everywhere/jwt/filter/JwtFilter.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index c194bb5..a756277 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -53,14 +53,14 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse // } // } - if (accessToken == null) { - filterChain.doFilter(request, response); - return; - } - - if (!validateToken(response, accessToken)) { - return; - } +// if (accessToken == null) { +// filterChain.doFilter(request, response); +// return; +// } +// +// if (!validateToken(response, accessToken)) { +// return; +// } //토큰에서 username과 role 획득 UserDto userDto = new UserDto(); From 0d8b3e2d9ef9fd22d1825f833bf806a538b80e36 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 02:06:04 +0900 Subject: [PATCH 43/51] fix : access header --- .../book_everywhere/jwt/filter/JwtFilter.java | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index a756277..241b32a 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -53,14 +53,15 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse // } // } -// if (accessToken == null) { -// filterChain.doFilter(request, response); -// return; -// } + if (accessToken == null) { + filterChain.doFilter(request, response); + return; + } // -// if (!validateToken(response, accessToken)) { -// return; -// } + if (!validateToken(response, accessToken)) { + logger.info("validateToken,validateToken,validateToken"); + return; + } //토큰에서 username과 role 획득 UserDto userDto = new UserDto(); @@ -80,12 +81,15 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse private boolean validateToken(HttpServletResponse response, String accessToken) throws IOException { try { - if (jwtProvider.isExpired(accessToken) || !ACCESS.getType().equals(jwtProvider.getCategory(accessToken))) { + if (jwtProvider.isExpired(accessToken) ) {//|| !ACCESS.getType().equals(jwtProvider.getCategory(accessToken))) { + logger.info("첫번째 에러가 좀 있구요"); sendErrorResponse(response, "Invalid or expired access token", HttpServletResponse.SC_UNAUTHORIZED); return false; } } catch (Exception e) { // 넓은 범위의 예외 처리를 통해 다양한 에러 상황을 처리할 수 있습니다. + logger.info("두번 째 401 토큰이 에러가 있습니다."); sendErrorResponse(response, "Token validation error", HttpServletResponse.SC_UNAUTHORIZED); + return false; } return true; From ca1ab6aec0ed965303e243c93aa6d7b59473ab72 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 16:48:33 +0900 Subject: [PATCH 44/51] =?UTF-8?q?fix=20:=20refresh=20Token=20=EC=82=AD?= =?UTF-8?q?=EC=A0=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/config/SecurityConfig.java | 9 +- .../jwt/controller/RefreshController.java | 86 --------------- .../book_everywhere/jwt/domain/Refresh.java | 26 ----- .../book_everywhere/jwt/dto/RefreshDto.java | 33 ------ .../jwt/filter/CustomLogoutFilter.java | 79 ------------- .../jwt/filter/CustomSuccessHandler.java | 16 +-- .../book_everywhere/jwt/filter/JwtFilter.java | 104 ++++++++---------- .../jwt/repository/RefreshRepository.java | 13 --- .../jwt/service/RefreshService.java | 11 -- .../jwt/service/impl/RefreshServiceImpl.java | 41 ------- .../jwt/token/JwtProvider.java | 32 +----- .../jwt/service/RefreshServiceTest.java | 71 ------------ 12 files changed, 52 insertions(+), 469 deletions(-) delete mode 100644 src/main/java/com/book_everywhere/jwt/controller/RefreshController.java delete mode 100644 src/main/java/com/book_everywhere/jwt/domain/Refresh.java delete mode 100644 src/main/java/com/book_everywhere/jwt/dto/RefreshDto.java delete mode 100644 src/main/java/com/book_everywhere/jwt/filter/CustomLogoutFilter.java delete mode 100644 src/main/java/com/book_everywhere/jwt/repository/RefreshRepository.java delete mode 100644 src/main/java/com/book_everywhere/jwt/service/RefreshService.java delete mode 100644 src/main/java/com/book_everywhere/jwt/service/impl/RefreshServiceImpl.java delete mode 100644 src/test/java/com/book_everywhere/domain/jwt/service/RefreshServiceTest.java diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index a06c885..5e3cc4e 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -1,8 +1,6 @@ package com.book_everywhere.auth.config; -import com.book_everywhere.jwt.filter.CustomLogoutFilter; import com.book_everywhere.jwt.filter.JwtFilter; -import com.book_everywhere.jwt.service.RefreshService; import com.book_everywhere.jwt.token.JwtProvider; import com.book_everywhere.auth.service.CustomOAuth2UserService; import com.book_everywhere.jwt.filter.CustomSuccessHandler; @@ -14,7 +12,6 @@ import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.logout.LogoutFilter; @@ -32,7 +29,6 @@ public class SecurityConfig { private final CustomOAuth2UserService customOAuth2UserService; private final CustomSuccessHandler customSuccessHandler; private final JwtProvider jwtProvider; - private final RefreshService refreshService; @Bean @@ -64,9 +60,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .csrf(AbstractHttpConfigurer::disable) .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) - .addFilterAfter(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class) -// .addFilterBefore(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) - .addFilterBefore(new CustomLogoutFilter(jwtProvider, refreshService), LogoutFilter.class) +// .addFilterAfter(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class) + .addFilterBefore(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() // 테스트 관련 url diff --git a/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java b/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java deleted file mode 100644 index 8987dcf..0000000 --- a/src/main/java/com/book_everywhere/jwt/controller/RefreshController.java +++ /dev/null @@ -1,86 +0,0 @@ -package com.book_everywhere.jwt.controller; - -import com.book_everywhere.auth.entity.Role; -import com.book_everywhere.jwt.dto.RefreshDto; -import com.book_everywhere.jwt.service.RefreshService; -import com.book_everywhere.jwt.token.JwtProvider; -import com.book_everywhere.common.dto.CMRespDto; -import com.book_everywhere.jwt.token.TokenType; -import io.jsonwebtoken.ExpiredJwtException; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import lombok.RequiredArgsConstructor; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RestController; - -import static com.book_everywhere.jwt.token.TokenType.ACCESS; -import static com.book_everywhere.jwt.token.TokenType.REFRESH; - - -@RestController -@RequiredArgsConstructor -public class RefreshController { - - private final JwtProvider jwtProvider; - private final RefreshService refreshService; - - @PostMapping("/api/refresh") - public CMRespDto reissue(HttpServletRequest request, HttpServletResponse response) { - - //get refresh token - String refresh = null; - Cookie[] cookies = request.getCookies(); - for (Cookie cookie : cookies) { - if (cookie.getName().equals(REFRESH.getType())) { - refresh = cookie.getValue(); - } - } - - if (refresh == null) { - //response status code - return new CMRespDto<>(HttpStatus.BAD_REQUEST, null, "refresh token null"); - } - - //expired check - try { - jwtProvider.isExpired(refresh); - } catch (ExpiredJwtException e) { - - //response status code - return new CMRespDto<>(HttpStatus.BAD_REQUEST, null, "refresh token expired"); - } - - // 토큰이 refresh인지 확인 (발급시 페이로드에 명시) - String category = jwtProvider.getCategory(refresh); - - if (!category.equals(REFRESH.getType())) { - return new CMRespDto<>(HttpStatus.BAD_REQUEST, null, "invalid refresh token"); - } - - boolean isExist = refreshService.리프레시토큰조회(refresh); - if (!isExist) { - return new CMRespDto<>(HttpStatus.BAD_REQUEST, null, "invalid refresh token"); - } - - - String username = jwtProvider.getUsername(refresh); - String role = jwtProvider.getRole(refresh); - - //make new JWT - String newAccess = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); - String newRefresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); - - refreshService.리프레시토큰삭제(refresh); - refreshService.리프레시토큰생성(new RefreshDto(username, newRefresh, REFRESH.getExpirationTime())); - - //response - response.setHeader(ACCESS.getType(), newAccess); - response.addCookie(jwtProvider.createCookie(REFRESH.getType(), newRefresh)); - - return new CMRespDto<>(HttpStatus.OK, null, "재발급 완료"); - } - - -} \ No newline at end of file diff --git a/src/main/java/com/book_everywhere/jwt/domain/Refresh.java b/src/main/java/com/book_everywhere/jwt/domain/Refresh.java deleted file mode 100644 index b624aba..0000000 --- a/src/main/java/com/book_everywhere/jwt/domain/Refresh.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.book_everywhere.jwt.domain; - -import com.book_everywhere.common.entity.BaseTimeEntity; -import jakarta.persistence.*; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Getter; -import lombok.NoArgsConstructor; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Entity -@Getter -public class Refresh extends BaseTimeEntity { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "refresh_id") - private Long id; - - private String username; - private String refresh; - private String expiration; - -} diff --git a/src/main/java/com/book_everywhere/jwt/dto/RefreshDto.java b/src/main/java/com/book_everywhere/jwt/dto/RefreshDto.java deleted file mode 100644 index 6129a5d..0000000 --- a/src/main/java/com/book_everywhere/jwt/dto/RefreshDto.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.book_everywhere.jwt.dto; - -import com.book_everywhere.jwt.domain.Refresh; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; - -import java.util.Date; - -@Data -@Builder -@AllArgsConstructor -public class RefreshDto { - private String username; - private String refresh; - private Long expiredMs; - - public Refresh toEntity(Date date) { - return Refresh.builder() - .username(username) - .refresh(refresh) - .expiration(date.toString()) - .build(); - } - - public static RefreshDto toDto(Refresh refresh) { - return RefreshDto.builder() - .username(refresh.getUsername()) - .refresh(refresh.getRefresh()) - .expiredMs(Long.parseLong(refresh.getExpiration())) - .build(); - } -} diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomLogoutFilter.java b/src/main/java/com/book_everywhere/jwt/filter/CustomLogoutFilter.java deleted file mode 100644 index a890ccc..0000000 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomLogoutFilter.java +++ /dev/null @@ -1,79 +0,0 @@ -package com.book_everywhere.jwt.filter; - - -import com.book_everywhere.jwt.dto.RefreshDto; -import com.book_everywhere.jwt.service.RefreshService; -import com.book_everywhere.jwt.token.JwtProvider; -import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import jakarta.servlet.ServletRequest; -import jakarta.servlet.ServletResponse; -import jakarta.servlet.http.Cookie; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; -import org.springframework.web.filter.GenericFilterBean; - -import java.io.IOException; - -import static com.book_everywhere.jwt.token.TokenType.REFRESH; - -@RequiredArgsConstructor -@Component -public class CustomLogoutFilter extends GenericFilterBean { - - private final JwtProvider jwtProvider; - private final RefreshService refreshService; - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - HttpServletRequest httpRequest = (HttpServletRequest) request; - HttpServletResponse httpResponse = (HttpServletResponse) response; - - if (isLogoutRequest(httpRequest)) { - handleLogout(httpRequest, httpResponse); - } else { - chain.doFilter(request, response); - } - } - - private boolean isLogoutRequest(HttpServletRequest request) { - return "POST".equalsIgnoreCase(request.getMethod()) && "/logout".equals(request.getRequestURI()); - } - - private void handleLogout(HttpServletRequest request, HttpServletResponse response) throws IOException { - String refreshToken = extractRefreshToken(request); - - if (refreshToken == null || !jwtProvider.validateToken(refreshToken)) { - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - - if (!refreshService.리프레시토큰조회(refreshToken)) { - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - RefreshDto refreshDto = refreshService.리프레시토큰객체조회(refreshToken); - refreshService.리프레시토큰삭제(refreshDto.getUsername()); - clearRefreshTokenCookie(response); - response.setStatus(HttpServletResponse.SC_OK); - } - - private String extractRefreshToken(HttpServletRequest request) { - if (request.getCookies() == null) return null; - for (Cookie cookie : request.getCookies()) { - if (REFRESH.getType().equals(cookie.getName())) { - return cookie.getValue(); - } - } - return null; - } - - private void clearRefreshTokenCookie(HttpServletResponse response) { - Cookie cookie = new Cookie(REFRESH.getType(), null); - cookie.setMaxAge(0); - cookie.setPath("/"); - response.addCookie(cookie); - } -} \ No newline at end of file diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java index 008ae05..9602ff7 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java @@ -1,16 +1,11 @@ package com.book_everywhere.jwt.filter; import com.book_everywhere.auth.dto.CustomOAuth2User; -import com.book_everywhere.auth.entity.Role; -import com.book_everywhere.jwt.dto.RefreshDto; -import com.book_everywhere.jwt.service.RefreshService; import com.book_everywhere.jwt.token.JwtProvider; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; @@ -21,15 +16,12 @@ import java.util.Collection; import java.util.Iterator; -import static com.book_everywhere.jwt.token.TokenType.ACCESS; -import static com.book_everywhere.jwt.token.TokenType.REFRESH; @RequiredArgsConstructor @Component public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { private final JwtProvider jwtProvider; - private final RefreshService refreshService; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { @@ -43,13 +35,9 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo GrantedAuthority auth = iterator.next(); String role = auth.getAuthority(); - String access = jwtProvider.createJwt(ACCESS.getType(), username, role, ACCESS.getExpirationTime()); - String refresh = jwtProvider.createJwt(REFRESH.getType(), username, role, REFRESH.getExpirationTime()); - refreshService.리프레시토큰생성(new RefreshDto(username, refresh, REFRESH.getExpirationTime())); + String token = jwtProvider.createJwt(username, role, 60*60*60*60L); - response.setHeader(ACCESS.getType(), access); - response.addCookie(jwtProvider.createCookie(ACCESS.getType(), access)); - response.addCookie(jwtProvider.createCookie(REFRESH.getType(), refresh)); + response.addCookie(jwtProvider.createCookie("Authorization", token)); response.sendRedirect("https://www.bookeverywhere.site/"); response.setStatus(HttpStatus.OK.value()); } diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java index 241b32a..2f47743 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java @@ -15,9 +15,8 @@ import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; -import java.io.PrintWriter; - -import static com.book_everywhere.jwt.token.TokenType.ACCESS; +import java.util.Arrays; +import java.util.Collections; @RequiredArgsConstructor public class JwtFilter extends OncePerRequestFilter { @@ -27,46 +26,59 @@ public class JwtFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //여기서 헤더가 access인 - String accessToken = request.getHeader(ACCESS.getType()); - logger.info(request); - -// String accessToken = null; -// Cookie[] cookies = request.getCookies(); -// if (cookies == null) { -// // 쿠키가 없음을 처리하는 로직 -// logger.info("@@@@@@@@@@@@@@@@@@@@@@"); - logger.info("@@@@@@@@@@@@@@@@@@@@@@"); - logger.info("@@@@@@@@@@@@@@@@@@@@@@"); - logger.info(accessToken); -// logger.info("쿠키없다는데? 왜없냐 ㄹㅇ"); -// filterChain.doFilter(request, response); -// return; -// } -// for (Cookie cookie : cookies) { -// logger.info("@@@@@@@@@@@@@@@@@@@@@@"); -// logger.info("@@@@@@@@@@@@@@@@@@@@@@"); -// logger.info("@@@@@@@@@@@@@@@@@@@@@@"); -// logger.info("@@@@@@@@@@@@@@@@@@@@@@"); -// logger.info(cookie); -// if (cookie.getName().equals(ACCESS.getType())) { -// accessToken = cookie.getValue(); -// } -// } - - if (accessToken == null) { + String authorization = null; + + Cookie[] cookies = request.getCookies(); + StringBuilder message = new StringBuilder(); + message.append("Request Method: ").append(request.getMethod()) + .append(", URL: ").append(request.getRequestURL()); + + // 헤더 정보 로깅 + Collections.list(request.getHeaderNames()).forEach(headerName -> + message.append(", ").append(headerName).append(": ").append(request.getHeader(headerName)) + ); + + // 파라미터 정보 로깅 (선택적) + request.getParameterMap().forEach((key, value) -> + message.append(", ").append(key).append(": ").append(Arrays.toString(value)) + ); + + logger.info(message.toString()); + if (cookies != null) { + for (Cookie cookie : cookies) { + logger.info(cookie.toString()); + if (cookie.getName().equals("Authorization")) { + authorization = cookie.getValue(); + } + } + } else { + logger.info("쿠키가 없습니다."); + } + + //Authorization 헤더 검증 + if (authorization == null) { + System.out.println("token null"); filterChain.doFilter(request, response); + //조건이 해당되면 메소드 종료 (필수) return; } -// - if (!validateToken(response, accessToken)) { - logger.info("validateToken,validateToken,validateToken"); + + //토큰 + String token = authorization; + + if (jwtProvider.isExpired(token)) { + + System.out.println("token expired"); + filterChain.doFilter(request, response); + + //조건이 해당되면 메소드 종료 (필수) return; } //토큰에서 username과 role 획득 UserDto userDto = new UserDto(); - userDto.setNickname(jwtProvider.getUsername(accessToken)); - userDto.setRole(jwtProvider.getRole(accessToken)); + userDto.setNickname(jwtProvider.getUsername(authorization)); + userDto.setRole(jwtProvider.getRole(authorization)); //UserDetails에 회원 정보 객체 담기 CustomOAuth2User customOAuth2User = new CustomOAuth2User(userDto); @@ -79,26 +91,4 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse filterChain.doFilter(request, response); } - private boolean validateToken(HttpServletResponse response, String accessToken) throws IOException { - try { - if (jwtProvider.isExpired(accessToken) ) {//|| !ACCESS.getType().equals(jwtProvider.getCategory(accessToken))) { - logger.info("첫번째 에러가 좀 있구요"); - sendErrorResponse(response, "Invalid or expired access token", HttpServletResponse.SC_UNAUTHORIZED); - return false; - } - } catch (Exception e) { // 넓은 범위의 예외 처리를 통해 다양한 에러 상황을 처리할 수 있습니다. - logger.info("두번 째 401 토큰이 에러가 있습니다."); - sendErrorResponse(response, "Token validation error", HttpServletResponse.SC_UNAUTHORIZED); - - return false; - } - return true; - } - - private void sendErrorResponse(HttpServletResponse response, String message, int status) throws IOException { - response.setStatus(status); - try (PrintWriter writer = response.getWriter()) { - writer.print(message); - } - } } \ No newline at end of file diff --git a/src/main/java/com/book_everywhere/jwt/repository/RefreshRepository.java b/src/main/java/com/book_everywhere/jwt/repository/RefreshRepository.java deleted file mode 100644 index 60b36f1..0000000 --- a/src/main/java/com/book_everywhere/jwt/repository/RefreshRepository.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.book_everywhere.jwt.repository; - -import com.book_everywhere.jwt.domain.Refresh; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface RefreshRepository extends JpaRepository { - Boolean existsByRefresh(String refresh); - - //유저네임 기준으로 삭제 이러면 모든 곳에서 로그아웃됨. - void deleteByUsername(String username); - - Refresh findByRefresh(String refresh); -} diff --git a/src/main/java/com/book_everywhere/jwt/service/RefreshService.java b/src/main/java/com/book_everywhere/jwt/service/RefreshService.java deleted file mode 100644 index 4bd824d..0000000 --- a/src/main/java/com/book_everywhere/jwt/service/RefreshService.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.book_everywhere.jwt.service; - -import com.book_everywhere.jwt.domain.Refresh; -import com.book_everywhere.jwt.dto.RefreshDto; - -public interface RefreshService { - void 리프레시토큰삭제(String username); - boolean 리프레시토큰조회(String refresh); - RefreshDto 리프레시토큰객체조회(String refresh); - void 리프레시토큰생성(RefreshDto refreshDto); -} diff --git a/src/main/java/com/book_everywhere/jwt/service/impl/RefreshServiceImpl.java b/src/main/java/com/book_everywhere/jwt/service/impl/RefreshServiceImpl.java deleted file mode 100644 index 6691a4d..0000000 --- a/src/main/java/com/book_everywhere/jwt/service/impl/RefreshServiceImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.book_everywhere.jwt.service.impl; - -import com.book_everywhere.jwt.domain.Refresh; -import com.book_everywhere.jwt.dto.RefreshDto; -import com.book_everywhere.jwt.repository.RefreshRepository; -import com.book_everywhere.jwt.service.RefreshService; -import jakarta.transaction.Transactional; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Service; - -import java.util.Date; - -@Service -@Transactional -@RequiredArgsConstructor -public class RefreshServiceImpl implements RefreshService { - - private final RefreshRepository refreshRepository; - - @Override - public void 리프레시토큰삭제(String username) { - refreshRepository.deleteByUsername(username); - } - - @Override - public boolean 리프레시토큰조회(String refresh) { - return refreshRepository.existsByRefresh(refresh); - } - - @Override - public void 리프레시토큰생성(RefreshDto refreshDto) { - Date date = new Date(System.currentTimeMillis() + refreshDto.getExpiredMs()); - refreshRepository.save(refreshDto.toEntity(date)); - } - - @Override - public RefreshDto 리프레시토큰객체조회(String refresh) { - Refresh token =refreshRepository.findByRefresh(refresh); - return RefreshDto.toDto(token); - } -} diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index d9afa81..7d6b1eb 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -14,9 +14,6 @@ @Component public class JwtProvider { - - private final Logger logger = LoggerFactory.getLogger(JwtProvider.class); - private SecretKey secretKey; public JwtProvider(@Value("${app.jwt.secret}") String secret) { @@ -31,17 +28,12 @@ public String getRole(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); } - public String getCategory(String token) { - return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("category", String.class); - } - public Boolean isExpired(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date()); } - public String createJwt(String category, String username, String role, Long expiredMs) { + public String createJwt( String username, String role, Long expiredMs) { return Jwts.builder() - .claim("category", category) .claim("username", username) .claim("role", role) .issuedAt(new Date(System.currentTimeMillis())) @@ -59,26 +51,4 @@ public Cookie createCookie(String key, String value) { return cookie; } - - public boolean validateToken(String token) { - try { - Jwts.parser() - .setSigningKey(secretKey) - .build() - .parseClaimsJws(token); - return true; - } catch (ExpiredJwtException e) { - logger.info("만료된 JWT 토큰입니다."); - } catch (UnsupportedJwtException e) { - logger.info("지원되지 않는 JWT 토큰입니다."); - } catch (MalformedJwtException e) { - logger.info("잘못된 형식의 JWT 토큰입니다."); - } catch (SecurityException e) { - logger.info("잘못된 JWT 서명입니다."); - } catch (IllegalArgumentException e) { - logger.info("JWT 토큰이 잘못되었습니다."); - } - // 위의 예외 중 하나라도 발생했다면, 토큰이 유효하지 않음을 의미합니다. - return false; - } } \ No newline at end of file diff --git a/src/test/java/com/book_everywhere/domain/jwt/service/RefreshServiceTest.java b/src/test/java/com/book_everywhere/domain/jwt/service/RefreshServiceTest.java deleted file mode 100644 index 82f489e..0000000 --- a/src/test/java/com/book_everywhere/domain/jwt/service/RefreshServiceTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.book_everywhere.domain.jwt.service; - -import com.book_everywhere.jwt.dto.RefreshDto; -import com.book_everywhere.jwt.repository.RefreshRepository; -import com.book_everywhere.jwt.service.RefreshService; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.transaction.annotation.Transactional; - -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.verify; - -@SpringBootTest -@Transactional -public class RefreshServiceTest { - - @Autowired - private RefreshService refreshService; - - @Autowired - private RefreshRepository refreshRepository; - - @Test - @DisplayName("Service_리프레시 토큰 생성 테스트") - void 리프레시토큰생성_테스트() { - RefreshDto refreshDto = new RefreshDto("ID", "token",1000L); // 1000L은 토큰 만료 시간 - given(refreshRepository.save(any())).willReturn(any()); - - // When - refreshService.리프레시토큰생성(refreshDto); - - // Then - verify(refreshRepository).save(any()); - } - - @Test - @DisplayName("Service_리프레시 토큰 조회 테스트") - void 리프레시토큰조회_테스트() { - // Given - String refreshToken = "token"; - given(refreshRepository.existsByRefresh(refreshToken)).willReturn(true); - - // When - boolean exists = refreshService.리프레시토큰조회(refreshToken); - - // Then - assertTrue(exists); - } - - @Test - @DisplayName("Service_리프레시 토큰 삭제 테스트") - void 리프레시토큰삭제_테스트() { - // Given - RefreshDto refreshDto = new RefreshDto("ID", "token", 1000L); // 1000L은 토큰 만료 시간 - given(refreshRepository.save(any())).willReturn(any()); - - // When - refreshService.리프레시토큰생성(refreshDto); - refreshService.리프레시토큰삭제(refreshDto.getUsername()); - - // Then - verify(refreshRepository).deleteByUsername(refreshDto.getUsername()); - // 삭제 메소드가 해당 토큰으로 호출되었는지 확인 - } - - -} From 0f0f92bcd6559ce740fbf1a2d9e139d9947fd90a Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 17:18:08 +0900 Subject: [PATCH 45/51] =?UTF-8?q?fix=20:=20=ED=95=84=ED=84=B0=20=EC=9C=84?= =?UTF-8?q?=EC=B9=98=20=EC=A1=B0=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/config/SecurityConfig.java | 6 ++---- .../book_everywhere/jwt/token/JwtProvider.java | 2 -- .../book_everywhere/jwt/token/TokenType.java | 18 ------------------ 3 files changed, 2 insertions(+), 24 deletions(-) delete mode 100644 src/main/java/com/book_everywhere/jwt/token/TokenType.java diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index 5e3cc4e..e2ce3ef 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -12,6 +12,7 @@ import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.logout.LogoutFilter; @@ -61,7 +62,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .formLogin(AbstractHttpConfigurer::disable) .httpBasic(AbstractHttpConfigurer::disable) // .addFilterAfter(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class) - .addFilterBefore(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class) + .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests .requestMatchers("/").permitAll() // 테스트 관련 url @@ -77,9 +78,6 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .userInfoEndpoint(userInfoEndpointConfig -> userInfoEndpointConfig.userService(customOAuth2UserService)) .successHandler(customSuccessHandler) -// .redirectionEndpoint(redirectionEndpointConfig -> -// redirectionEndpointConfig.baseUri("https://api.bookeverywhere.site/oauth2/authorization/kakao" )) - ) ; return http.build(); diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java index 7d6b1eb..fc05ed5 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java @@ -2,8 +2,6 @@ import io.jsonwebtoken.*; import jakarta.servlet.http.Cookie; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; diff --git a/src/main/java/com/book_everywhere/jwt/token/TokenType.java b/src/main/java/com/book_everywhere/jwt/token/TokenType.java deleted file mode 100644 index 1df79dd..0000000 --- a/src/main/java/com/book_everywhere/jwt/token/TokenType.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.book_everywhere.jwt.token; - -import lombok.Getter; - -@Getter -public enum TokenType { - ACCESS("access", 600000L), - REFRESH("refresh", 86400000L); - - private final String type; - private final Long expirationTime; - - TokenType(String type, Long expirationTime) { - this.type = type; - this.expirationTime = expirationTime; - } - -} From f72a88c36956a290e3c68d58b8e9a2cbb220d121 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 18:26:38 +0900 Subject: [PATCH 46/51] =?UTF-8?q?fix=20:=20=ED=95=84=ED=84=B0=20=EC=9C=84?= =?UTF-8?q?=EC=B9=98=20=EC=A1=B0=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/book_everywhere/auth/config/SecurityConfig.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index e2ce3ef..aa8501a 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -14,8 +14,6 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter; import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.security.web.authentication.logout.LogoutFilter; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; From bebbc9219f949207c112bb9ea86ace979a62e8af Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Tue, 2 Apr 2024 19:50:35 +0900 Subject: [PATCH 47/51] =?UTF-8?q?feat=20:=20=EB=A0=88=EB=94=94=EC=8A=A4=20?= =?UTF-8?q?=EC=97=B0=EB=8F=99=20=EC=84=A4=EC=A0=95=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 레디스를 EC2에 설치 및 연동 테스트가 마무리 되었습니다. --- build.gradle | 2 + .../book_everywhere/redis/RedisConfig.java | 48 +++++++++++ .../book_everywhere/redis/RedisService.java | 67 +++++++++++++++ .../domain/redis/RedisCrudTest.java | 85 +++++++++++++++++++ 4 files changed, 202 insertions(+) create mode 100644 src/main/java/com/book_everywhere/redis/RedisConfig.java create mode 100644 src/main/java/com/book_everywhere/redis/RedisService.java create mode 100644 src/test/java/com/book_everywhere/domain/redis/RedisCrudTest.java diff --git a/build.gradle b/build.gradle index c9fa796..858d25a 100644 --- a/build.gradle +++ b/build.gradle @@ -42,6 +42,8 @@ dependencies { implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2' //log를 위한 추가 + //Redis + implementation 'org.springframework.boot:spring-boot-starter-data-redis' //test를 위한 추가 runtimeOnly 'com.h2database:h2' diff --git a/src/main/java/com/book_everywhere/redis/RedisConfig.java b/src/main/java/com/book_everywhere/redis/RedisConfig.java new file mode 100644 index 0000000..0554d92 --- /dev/null +++ b/src/main/java/com/book_everywhere/redis/RedisConfig.java @@ -0,0 +1,48 @@ +package com.book_everywhere.redis; + +import lombok.RequiredArgsConstructor; +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.repository.configuration.EnableRedisRepositories; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +@RequiredArgsConstructor +@Configuration +@EnableRedisRepositories +public class RedisConfig { + +// private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class); + + @Value("${spring.redis.host}") + private String redisHost; + + @Value("${spring.redis.port}") + private int redisPort; + +// @PostConstruct +// public void postConstruct() { +// logger.info("Redis Host: {}", redisHost); +// logger.info("Redis Port: {}", redisPort); +// } + + // RedisProperties로 yaml에 저장한 host, post를 연결 + @Bean + public RedisConnectionFactory redisConnectionFactory() { + return new LettuceConnectionFactory(redisHost, redisPort); + } + + // serializer 설정으로 redis-cli를 통해 직접 데이터를 조회할 수 있도록 설정 + @Bean + public RedisTemplate redisTemplate() { + RedisTemplate redisTemplate = new RedisTemplate<>(); + redisTemplate.setKeySerializer(new StringRedisSerializer()); + redisTemplate.setValueSerializer(new StringRedisSerializer()); + redisTemplate.setConnectionFactory(redisConnectionFactory()); + + return redisTemplate; + } +} \ No newline at end of file diff --git a/src/main/java/com/book_everywhere/redis/RedisService.java b/src/main/java/com/book_everywhere/redis/RedisService.java new file mode 100644 index 0000000..1ddf5cc --- /dev/null +++ b/src/main/java/com/book_everywhere/redis/RedisService.java @@ -0,0 +1,67 @@ +package com.book_everywhere.redis; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.HashOperations; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +@Slf4j +@Component +@RequiredArgsConstructor +public class RedisService { + private final RedisTemplate redisTemplate; + + public void setValues(String key, String data) { + ValueOperations values = redisTemplate.opsForValue(); + values.set(key, data); + } + + public void setValues(String key, String data, Duration duration) { + ValueOperations values = redisTemplate.opsForValue(); + values.set(key, data, duration); + } + + @Transactional(readOnly = true) + public String getValues(String key) { + ValueOperations values = redisTemplate.opsForValue(); + if (values.get(key) == null) { + return "false"; + } + return (String) values.get(key); + } + + public void deleteValues(String key) { + redisTemplate.delete(key); + } + + public void expireValues(String key, int timeout) { + redisTemplate.expire(key, timeout, TimeUnit.MILLISECONDS); + } + + public void setHashOps(String key, Map data) { + HashOperations values = redisTemplate.opsForHash(); + values.putAll(key, data); + } + + @Transactional(readOnly = true) + public String getHashOps(String key, String hashKey) { + HashOperations values = redisTemplate.opsForHash(); + return Boolean.TRUE.equals(values.hasKey(key, hashKey)) ? (String) redisTemplate.opsForHash().get(key, hashKey) : ""; + } + + public void deleteHashOps(String key, String hashKey) { + HashOperations values = redisTemplate.opsForHash(); + values.delete(key, hashKey); + } + + public boolean checkExistsValue(String value) { + return !value.equals("false"); + } +} \ No newline at end of file diff --git a/src/test/java/com/book_everywhere/domain/redis/RedisCrudTest.java b/src/test/java/com/book_everywhere/domain/redis/RedisCrudTest.java new file mode 100644 index 0000000..259475d --- /dev/null +++ b/src/test/java/com/book_everywhere/domain/redis/RedisCrudTest.java @@ -0,0 +1,85 @@ +package com.book_everywhere.domain.redis; + +import com.book_everywhere.redis.RedisService; +import lombok.extern.slf4j.Slf4j; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.time.Duration; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.awaitility.Awaitility.await; + +@Slf4j +@SpringBootTest +class RedisCrudTest { + final String KEY = "key"; + final String VALUE = "value"; + final Duration DURATION = Duration.ofMillis(5000); + @Autowired + private RedisService redisService; + + @BeforeEach + void shutDown() { + redisService.setValues(KEY, VALUE, DURATION); + } + + @AfterEach + void tearDown() { + redisService.deleteValues(KEY); + } + + @Test + @DisplayName("Redis에 데이터를 저장하면 정상적으로 조회된다.") + void saveAndFindTest() throws Exception { + // when + String findValue = redisService.getValues(KEY); + + // then + assertThat(VALUE).isEqualTo(findValue); + } + + @Test + @DisplayName("Redis에 저장된 데이터를 수정할 수 있다.") + void updateTest() throws Exception { + // given + String updateValue = "updateValue"; + redisService.setValues(KEY, updateValue, DURATION); + + // when + String findValue = redisService.getValues(KEY); + + // then + assertThat(updateValue).isEqualTo(findValue); + assertThat(VALUE).isNotEqualTo(findValue); + } + + @Test + @DisplayName("Redis에 저장된 데이터를 삭제할 수 있다.") + void deleteTest() throws Exception { + // when + redisService.deleteValues(KEY); + String findValue = redisService.getValues(KEY); + + // then + assertThat(findValue).isEqualTo("false"); + } + + @Test + @DisplayName("Redis에 저장된 데이터는 만료시간이 지나면 삭제된다.") + void expiredTest() throws Exception { + // when + String findValue = redisService.getValues(KEY); + await().pollDelay(Duration.ofMillis(6000)).untilAsserted( + () -> { + String expiredValue = redisService.getValues(KEY); + assertThat(expiredValue).isNotEqualTo(findValue); + assertThat(expiredValue).isEqualTo("false"); + } + ); + } +} \ No newline at end of file From 1ffa31d84928069c41c6d0a983564b8213b4b9ad Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Wed, 3 Apr 2024 02:39:57 +0900 Subject: [PATCH 48/51] =?UTF-8?q?feat=20:=20=EC=A2=8B=EC=95=84=EC=9A=94=20?= =?UTF-8?q?=EC=BA=90=EC=8B=B1=EA=B8=B0=EB=8A=A5=20=EC=99=84=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 레디스 좋아요 기능을 캐싱하였습니다. --- .../likes/service/LikesCachingService.java | 8 ++++++ .../service/LikesCachingServiceImpl.java | 26 +++++++++++++++++++ .../likes/service/LikesServiceImpl.java | 3 +++ .../review/service/ReviewServiceImpl.java | 14 +++++----- 4 files changed, 45 insertions(+), 6 deletions(-) create mode 100644 src/main/java/com/book_everywhere/likes/service/LikesCachingService.java create mode 100644 src/main/java/com/book_everywhere/likes/service/LikesCachingServiceImpl.java diff --git a/src/main/java/com/book_everywhere/likes/service/LikesCachingService.java b/src/main/java/com/book_everywhere/likes/service/LikesCachingService.java new file mode 100644 index 0000000..56ee641 --- /dev/null +++ b/src/main/java/com/book_everywhere/likes/service/LikesCachingService.java @@ -0,0 +1,8 @@ +package com.book_everywhere.likes.service; + +public interface LikesCachingService { + + Long 좋아요캐시업데이트(Long reviewId); + + void 좋아요캐시무효화(Long reviewId); +} diff --git a/src/main/java/com/book_everywhere/likes/service/LikesCachingServiceImpl.java b/src/main/java/com/book_everywhere/likes/service/LikesCachingServiceImpl.java new file mode 100644 index 0000000..9820e91 --- /dev/null +++ b/src/main/java/com/book_everywhere/likes/service/LikesCachingServiceImpl.java @@ -0,0 +1,26 @@ +package com.book_everywhere.likes.service; + +import com.book_everywhere.likes.repository.LikesRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +import org.springframework.stereotype.Service; + +@Service +@RequiredArgsConstructor +public class LikesCachingServiceImpl implements LikesCachingService { + + private final LikesRepository likesRepository; + + @Override + @CachePut(value = "likesCount", key = "#reviewId") + public Long 좋아요캐시업데이트(Long reviewId) { + return likesRepository.countByReviewId(reviewId); + } + + @Override + @CacheEvict(value = "likesCount", key = "#reviewId") + public void 좋아요캐시무효화(Long reviewId) { + + } +} diff --git a/src/main/java/com/book_everywhere/likes/service/LikesServiceImpl.java b/src/main/java/com/book_everywhere/likes/service/LikesServiceImpl.java index 455566f..eba6068 100644 --- a/src/main/java/com/book_everywhere/likes/service/LikesServiceImpl.java +++ b/src/main/java/com/book_everywhere/likes/service/LikesServiceImpl.java @@ -18,12 +18,14 @@ public class LikesServiceImpl implements LikesService { private final LikesRepository likesRepository; private final UserRepository userRepository; + private final LikesCachingService likesCachingService; @Override @Transactional public void 좋아요(Long socialId, Long review_id) { User user = userRepository.findBySocialId(socialId).orElseThrow(); likesRepository.mLike(user.getId(),review_id); + likesCachingService.좋아요캐시무효화(review_id); } @Override @@ -31,6 +33,7 @@ public class LikesServiceImpl implements LikesService { public void 좋아요취소(Long socialId, Long review_id) { User user = userRepository.findBySocialId(socialId).orElseThrow(); likesRepository.mUnLike(user.getId(), review_id); + likesCachingService.좋아요캐시무효화(review_id); } } diff --git a/src/main/java/com/book_everywhere/review/service/ReviewServiceImpl.java b/src/main/java/com/book_everywhere/review/service/ReviewServiceImpl.java index adcb01a..ae3355e 100644 --- a/src/main/java/com/book_everywhere/review/service/ReviewServiceImpl.java +++ b/src/main/java/com/book_everywhere/review/service/ReviewServiceImpl.java @@ -3,6 +3,7 @@ import com.book_everywhere.book.entity.Book; import com.book_everywhere.book.repository.BookRepository; import com.book_everywhere.likes.repository.LikesRepository; +import com.book_everywhere.likes.service.LikesCachingService; import com.book_everywhere.pin.entity.Pin; import com.book_everywhere.pin.repository.PinRepository; import com.book_everywhere.review.entity.Review; @@ -32,6 +33,7 @@ public class ReviewServiceImpl implements ReviewService { private final UserRepository userRepository; private final TaggedService taggedService; private final LikesRepository likesRepository; + private final LikesCachingService likesCachingService; //사용자 검증에 메소드 @@ -74,7 +76,7 @@ public class ReviewServiceImpl implements ReviewService { User user = userRepository.findBySocialId(socialId).orElseThrow(); return init.stream().map(review -> { - Long likeCount = likesRepository.countByReviewId(review.getId()); + Long likeCount = likesCachingService.좋아요캐시업데이트(review.getId()); boolean likeState = likesRepository.existsByUserIdAndReviewId(user.getId(), review.getId()); return ReviewDto.toDto(review, likeCount, likeState); }).toList(); @@ -90,7 +92,7 @@ public class ReviewServiceImpl implements ReviewService { User user = userRepository.findBySocialId(socialId).orElseThrow(); return init.stream().map(review -> { - Long likeCount = likesRepository.countByReviewId(review.getId()); + Long likeCount = likesCachingService.좋아요캐시업데이트(review.getId()); boolean likeState = likesRepository.existsByUserIdAndReviewId(user.getId(), review.getId()); return ReviewDto.toDto(review, likeCount, likeState); }).toList(); @@ -102,7 +104,7 @@ public class ReviewServiceImpl implements ReviewService { User user = userRepository.findBySocialId(socialId).orElseThrow(); return init.stream().map(review -> { - Long likeCount = likesRepository.countByReviewId(review.getId()); + Long likeCount = likesCachingService.좋아요캐시업데이트(review.getId()); boolean likeState = likesRepository.existsByUserIdAndReviewId(user.getId(), review.getId()); return ReviewDto.toDto(review, likeCount, likeState); }).toList(); @@ -115,7 +117,7 @@ public class ReviewServiceImpl implements ReviewService { Review review = reviewRepository.findById(review_id).orElseThrow( () -> new EntityNotFoundException(CustomErrorCode.REVIEW_NOT_FOUND)); - Long likeCount = likesRepository.countByReviewId(review.getId()); + Long likeCount = likesCachingService.좋아요캐시업데이트(review.getId()); boolean likeState = likesRepository.existsByUserIdAndReviewId(user.getId(), review.getId()); return ReviewDto.toDto(review, likeCount, likeState); } @@ -128,7 +130,7 @@ public class ReviewServiceImpl implements ReviewService { Optional optionalUser = userRepository.findBySocialId(socialId); return init.stream().map(review -> { - Long likeCount = likesRepository.countByReviewId(review.getId()); + Long likeCount = likesCachingService.좋아요캐시업데이트(review.getId()); boolean likeState = optionalUser .map(user -> likesRepository.existsByUserIdAndReviewId(user.getId(), review.getId())) .orElse(false); @@ -143,7 +145,7 @@ public class ReviewServiceImpl implements ReviewService { Optional optionalUser = userRepository.findBySocialId(socialId); return init.stream().map(review -> { - Long likeCount = likesRepository.countByReviewId(review.getId()); + Long likeCount = likesCachingService.좋아요캐시업데이트(review.getId()); boolean likeState = optionalUser .map(user -> likesRepository.existsByUserIdAndReviewId(user.getId(), review.getId())) .orElse(false); From d2efb1164a4ccb0117d2a71b08aa294898ecba4a Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 8 Apr 2024 16:52:15 +0900 Subject: [PATCH 49/51] =?UTF-8?q?feature=20:=20=EC=A2=8B=EC=95=84=EC=9A=94?= =?UTF-8?q?=20Redis=20=EC=BA=90=EC=8B=B1=EC=B2=98=EB=A6=AC=20=EC=99=84?= =?UTF-8?q?=EB=A3=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/book_everywhere/BookEverywhereApplication.java | 2 ++ .../com/book_everywhere/auth/config/SecurityConfig.java | 3 ++- .../likes/service/LikesCachingServiceImpl.java | 7 ++++++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/book_everywhere/BookEverywhereApplication.java b/src/main/java/com/book_everywhere/BookEverywhereApplication.java index f56f07f..0b5d79f 100644 --- a/src/main/java/com/book_everywhere/BookEverywhereApplication.java +++ b/src/main/java/com/book_everywhere/BookEverywhereApplication.java @@ -2,7 +2,9 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; +@EnableCaching @SpringBootApplication public class BookEverywhereApplication { public static void main(String[] args) { diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java index aa8501a..250d9e4 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java @@ -65,10 +65,11 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { .requestMatchers("/").permitAll() // 테스트 관련 url .requestMatchers("/health", "/env", "/test/**", "/swagger-ui/**").permitAll() + .requestMatchers("/api/reviews").permitAll() // 비회원도 볼수있는 url .requestMatchers("/api/review", "/api/map", "/api/tags", "/api/data/**").permitAll() // 나머지 - .requestMatchers("/api/**").hasAuthority("ROLE_MEMBER") +// .requestMatchers("/api/**").hasAuthority("ROLE_MEMBER") .anyRequest().authenticated() ) .oauth2Login(oauth2Login -> diff --git a/src/main/java/com/book_everywhere/likes/service/LikesCachingServiceImpl.java b/src/main/java/com/book_everywhere/likes/service/LikesCachingServiceImpl.java index 9820e91..99f8b9d 100644 --- a/src/main/java/com/book_everywhere/likes/service/LikesCachingServiceImpl.java +++ b/src/main/java/com/book_everywhere/likes/service/LikesCachingServiceImpl.java @@ -2,19 +2,24 @@ import com.book_everywhere.likes.repository.LikesRepository; import lombok.RequiredArgsConstructor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class LikesCachingServiceImpl implements LikesCachingService { + private static final Logger logger = LoggerFactory.getLogger(LikesCachingServiceImpl.class); private final LikesRepository likesRepository; @Override - @CachePut(value = "likesCount", key = "#reviewId") + @Cacheable(value = "likesCount", key = "#reviewId") public Long 좋아요캐시업데이트(Long reviewId) { + logger.info(reviewId+"의 캐시가 없데이트 되었습니다."); return likesRepository.countByReviewId(reviewId); } From aace410512c344146d804b326c64cb99dbfbf677 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 8 Apr 2024 16:57:43 +0900 Subject: [PATCH 50/51] =?UTF-8?q?style:=20=ED=8C=A8=ED=82=A4=EC=A7=80=20?= =?UTF-8?q?=EA=B5=AC=EC=A1=B0=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/config/SecurityConfig.java | 16 ++++---- .../auth/dto/CustomOAuth2User.java | 3 +- .../auth/dto/OAuthAttributes.java | 6 +-- .../{ => common}/auth/dto/UserDto.java | 2 +- .../{ => common}/auth/entity/Role.java | 2 +- .../{ => common}/auth/entity/User.java | 10 ++--- .../auth/repository/UserRepository.java | 4 +- .../auth/service/CustomOAuth2UserService.java | 28 ++++--------- .../exception/GlobalExceptionHandler.java | 6 +-- .../exception/customs/CustomErrorCode.java | 2 +- .../exception/customs/CustomException.java | 2 +- .../customs/EntityNotFoundException.java | 2 +- .../customs/PropertyBadRequestException.java | 2 +- .../exception/customs/SQLException.java | 2 +- .../jwt/filter/CustomSuccessHandler.java | 6 +-- .../{ => common}/jwt/filter/JwtFilter.java | 8 ++-- .../{ => common}/jwt/token/JwtProvider.java | 2 +- .../{ => common}/redis/RedisConfig.java | 2 +- .../{ => common}/redis/RedisService.java | 2 +- .../{ => common}/swagger/SwaggerConfig.java | 2 +- .../book/controller/BookController.java | 6 +-- .../book/dto/BookDocumentDto.java | 2 +- .../{ => domain}/book/dto/BookDto.java | 5 +-- .../{ => domain}/book/dto/BookRespDto.java | 5 +-- .../{ => domain}/book/entity/Book.java | 4 +- .../book/repository/BookRepository.java | 5 +-- .../book/service/BookService.java | 6 +-- .../book/service/BookServiceImpl.java | 18 ++++----- .../data/controller/DataController.java | 6 +-- .../{ => domain}/data/dto/AllDataDto.java | 9 ++--- .../data/service/DataService.java | 40 +++++++++---------- .../{ => domain}/likes/entity/Likes.java | 6 +-- .../likes/repository/LikesRepository.java | 4 +- .../likes/service/LikesCachingService.java | 2 +- .../service/LikesCachingServiceImpl.java | 4 +- .../likes/service/LikesService.java | 2 +- .../likes/service/LikesServiceImpl.java | 11 ++--- .../pin/controller/PinController.java | 14 +++---- .../{ => domain}/pin/dto/PinDto.java | 6 +-- .../{ => domain}/pin/dto/PinRespDto.java | 4 +- .../pin/dto/PinWithTagCountRespDto.java | 7 ++-- .../{ => domain}/pin/dto/VisitRespDto.java | 2 +- .../{ => domain}/pin/entity/Pin.java | 6 +-- .../{ => domain}/pin/entity/Visit.java | 4 +- .../pin/repository/PinRepository.java | 5 +-- .../pin/repository/VisitRepository.java | 5 +-- .../{ => domain}/pin/service/PinService.java | 8 ++-- .../pin/service/PinServiceImpl.java | 22 +++++----- .../pin/service/VisitService.java | 4 +- .../pin/service/VisitServiceImpl.java | 20 +++++----- .../review/controller/ReviewController.java | 20 +++++----- .../{ => domain}/review/dto/ReviewDto.java | 7 +--- .../review/dto/ReviewRespDto.java | 15 ++++--- .../{ => domain}/review/entity/Review.java | 8 ++-- .../review/repository/ReviewRepository.java | 7 +--- .../review/service/ReviewService.java | 7 ++-- .../review/service/ReviewServiceImpl.java | 37 +++++++++-------- .../tag/controller/TagController.java | 6 +-- .../{ => domain}/tag/dto/TagCountRespDto.java | 2 +- .../{ => domain}/tag/dto/TagDto.java | 2 +- .../{ => domain}/tag/dto/TagRespDto.java | 2 +- .../{ => domain}/tag/dto/TaggedDto.java | 2 +- .../{ => domain}/tag/entity/Category.java | 2 +- .../{ => domain}/tag/entity/Tag.java | 2 +- .../{ => domain}/tag/entity/Tagged.java | 6 +-- .../tag/repository/CategoryRepository.java | 4 +- .../tag/repository/TagRepository.java | 5 +-- .../tag/repository/TaggedRepository.java | 7 +--- .../tag/service/TaggedService.java | 6 +-- .../tag/service/TaggedServiceImpl.java | 26 ++++++------ .../domain/auth/UserTestBuilder.java | 4 +- .../domain/book/dto/BookRespDtoBuilder.java | 3 +- .../book/repository/BookRepositoryTest.java | 15 ++++--- .../likes/repository/LikesRepositoryTest.java | 17 ++++---- .../domain/pin/dto/PinRespDtoTestBuilder.java | 4 +- .../domain/pin/service/PinServiceTest.java | 13 +++--- .../domain/redis/RedisCrudTest.java | 2 +- .../review/dto/ReviewRespDtoTestBuilder.java | 13 +++--- .../review/service/ReviewServiceTest.java | 19 +++++---- 79 files changed, 282 insertions(+), 332 deletions(-) rename src/main/java/com/book_everywhere/{ => common}/auth/config/SecurityConfig.java (87%) rename src/main/java/com/book_everywhere/{ => common}/auth/dto/CustomOAuth2User.java (91%) rename src/main/java/com/book_everywhere/{ => common}/auth/dto/OAuthAttributes.java (90%) rename src/main/java/com/book_everywhere/{ => common}/auth/dto/UserDto.java (70%) rename src/main/java/com/book_everywhere/{ => common}/auth/entity/Role.java (50%) rename src/main/java/com/book_everywhere/{ => common}/auth/entity/User.java (83%) rename src/main/java/com/book_everywhere/{ => common}/auth/repository/UserRepository.java (75%) rename src/main/java/com/book_everywhere/{ => common}/auth/service/CustomOAuth2UserService.java (65%) rename src/main/java/com/book_everywhere/{ => common}/exception/GlobalExceptionHandler.java (77%) rename src/main/java/com/book_everywhere/{ => common}/exception/customs/CustomErrorCode.java (95%) rename src/main/java/com/book_everywhere/{ => common}/exception/customs/CustomException.java (83%) rename src/main/java/com/book_everywhere/{ => common}/exception/customs/EntityNotFoundException.java (75%) rename src/main/java/com/book_everywhere/{ => common}/exception/customs/PropertyBadRequestException.java (75%) rename src/main/java/com/book_everywhere/{ => common}/exception/customs/SQLException.java (72%) rename src/main/java/com/book_everywhere/{ => common}/jwt/filter/CustomSuccessHandler.java (90%) rename src/main/java/com/book_everywhere/{ => common}/jwt/filter/JwtFilter.java (93%) rename src/main/java/com/book_everywhere/{ => common}/jwt/token/JwtProvider.java (97%) rename src/main/java/com/book_everywhere/{ => common}/redis/RedisConfig.java (97%) rename src/main/java/com/book_everywhere/{ => common}/redis/RedisService.java (98%) rename src/main/java/com/book_everywhere/{ => common}/swagger/SwaggerConfig.java (95%) rename src/main/java/com/book_everywhere/{ => domain}/book/controller/BookController.java (88%) rename src/main/java/com/book_everywhere/{ => domain}/book/dto/BookDocumentDto.java (85%) rename src/main/java/com/book_everywhere/{ => domain}/book/dto/BookDto.java (81%) rename src/main/java/com/book_everywhere/{ => domain}/book/dto/BookRespDto.java (78%) rename src/main/java/com/book_everywhere/{ => domain}/book/entity/Book.java (87%) rename src/main/java/com/book_everywhere/{ => domain}/book/repository/BookRepository.java (84%) rename src/main/java/com/book_everywhere/{ => domain}/book/service/BookService.java (59%) rename src/main/java/com/book_everywhere/{ => domain}/book/service/BookServiceImpl.java (76%) rename src/main/java/com/book_everywhere/{ => domain}/data/controller/DataController.java (86%) rename src/main/java/com/book_everywhere/{ => domain}/data/dto/AllDataDto.java (71%) rename src/main/java/com/book_everywhere/{ => domain}/data/service/DataService.java (82%) rename src/main/java/com/book_everywhere/{ => domain}/likes/entity/Likes.java (85%) rename src/main/java/com/book_everywhere/{ => domain}/likes/repository/LikesRepository.java (88%) rename src/main/java/com/book_everywhere/{ => domain}/likes/service/LikesCachingService.java (74%) rename src/main/java/com/book_everywhere/{ => domain}/likes/service/LikesCachingServiceImpl.java (85%) rename src/main/java/com/book_everywhere/{ => domain}/likes/service/LikesService.java (74%) rename src/main/java/com/book_everywhere/{ => domain}/likes/service/LikesServiceImpl.java (73%) rename src/main/java/com/book_everywhere/{ => domain}/pin/controller/PinController.java (88%) rename src/main/java/com/book_everywhere/{ => domain}/pin/dto/PinDto.java (85%) rename src/main/java/com/book_everywhere/{ => domain}/pin/dto/PinRespDto.java (86%) rename src/main/java/com/book_everywhere/{ => domain}/pin/dto/PinWithTagCountRespDto.java (85%) rename src/main/java/com/book_everywhere/{ => domain}/pin/dto/VisitRespDto.java (84%) rename src/main/java/com/book_everywhere/{ => domain}/pin/entity/Pin.java (88%) rename src/main/java/com/book_everywhere/{ => domain}/pin/entity/Visit.java (92%) rename src/main/java/com/book_everywhere/{ => domain}/pin/repository/PinRepository.java (90%) rename src/main/java/com/book_everywhere/{ => domain}/pin/repository/VisitRepository.java (82%) rename src/main/java/com/book_everywhere/{ => domain}/pin/service/PinService.java (66%) rename src/main/java/com/book_everywhere/{ => domain}/pin/service/PinServiceImpl.java (80%) rename src/main/java/com/book_everywhere/{ => domain}/pin/service/VisitService.java (52%) rename src/main/java/com/book_everywhere/{ => domain}/pin/service/VisitServiceImpl.java (69%) rename src/main/java/com/book_everywhere/{ => domain}/review/controller/ReviewController.java (91%) rename src/main/java/com/book_everywhere/{ => domain}/review/dto/ReviewDto.java (80%) rename src/main/java/com/book_everywhere/{ => domain}/review/dto/ReviewRespDto.java (67%) rename src/main/java/com/book_everywhere/{ => domain}/review/entity/Review.java (90%) rename src/main/java/com/book_everywhere/{ => domain}/review/repository/ReviewRepository.java (83%) rename src/main/java/com/book_everywhere/{ => domain}/review/service/ReviewService.java (81%) rename src/main/java/com/book_everywhere/{ => domain}/review/service/ReviewServiceImpl.java (90%) rename src/main/java/com/book_everywhere/{ => domain}/tag/controller/TagController.java (79%) rename src/main/java/com/book_everywhere/{ => domain}/tag/dto/TagCountRespDto.java (79%) rename src/main/java/com/book_everywhere/{ => domain}/tag/dto/TagDto.java (81%) rename src/main/java/com/book_everywhere/{ => domain}/tag/dto/TagRespDto.java (83%) rename src/main/java/com/book_everywhere/{ => domain}/tag/dto/TaggedDto.java (88%) rename src/main/java/com/book_everywhere/{ => domain}/tag/entity/Category.java (92%) rename src/main/java/com/book_everywhere/{ => domain}/tag/entity/Tag.java (93%) rename src/main/java/com/book_everywhere/{ => domain}/tag/entity/Tagged.java (89%) rename src/main/java/com/book_everywhere/{ => domain}/tag/repository/CategoryRepository.java (57%) rename src/main/java/com/book_everywhere/{ => domain}/tag/repository/TagRepository.java (74%) rename src/main/java/com/book_everywhere/{ => domain}/tag/repository/TaggedRepository.java (85%) rename src/main/java/com/book_everywhere/{ => domain}/tag/service/TaggedService.java (56%) rename src/main/java/com/book_everywhere/{ => domain}/tag/service/TaggedServiceImpl.java (73%) diff --git a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/common/auth/config/SecurityConfig.java similarity index 87% rename from src/main/java/com/book_everywhere/auth/config/SecurityConfig.java rename to src/main/java/com/book_everywhere/common/auth/config/SecurityConfig.java index aa8501a..142140e 100644 --- a/src/main/java/com/book_everywhere/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/common/auth/config/SecurityConfig.java @@ -1,9 +1,9 @@ -package com.book_everywhere.auth.config; +package com.book_everywhere.common.auth.config; -import com.book_everywhere.jwt.filter.JwtFilter; -import com.book_everywhere.jwt.token.JwtProvider; -import com.book_everywhere.auth.service.CustomOAuth2UserService; -import com.book_everywhere.jwt.filter.CustomSuccessHandler; +import com.book_everywhere.common.auth.service.CustomOAuth2UserService; +import com.book_everywhere.common.jwt.filter.JwtFilter; +import com.book_everywhere.common.jwt.token.JwtProvider; +import com.book_everywhere.common.jwt.filter.CustomSuccessHandler; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -62,14 +62,16 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // .addFilterAfter(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class) .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests + .requestMatchers("/").permitAll() // 테스트 관련 url + .requestMatchers("/api/**").permitAll() .requestMatchers("/health", "/env", "/test/**", "/swagger-ui/**").permitAll() // 비회원도 볼수있는 url .requestMatchers("/api/review", "/api/map", "/api/tags", "/api/data/**").permitAll() // 나머지 - .requestMatchers("/api/**").hasAuthority("ROLE_MEMBER") - .anyRequest().authenticated() +// .requestMatchers("/api/**").hasAuthority("ROLE_MEMBER") +// .anyRequest().authenticated() ) .oauth2Login(oauth2Login -> oauth2Login diff --git a/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java b/src/main/java/com/book_everywhere/common/auth/dto/CustomOAuth2User.java similarity index 91% rename from src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java rename to src/main/java/com/book_everywhere/common/auth/dto/CustomOAuth2User.java index d58894a..f0459da 100644 --- a/src/main/java/com/book_everywhere/auth/dto/CustomOAuth2User.java +++ b/src/main/java/com/book_everywhere/common/auth/dto/CustomOAuth2User.java @@ -1,6 +1,5 @@ -package com.book_everywhere.auth.dto; +package com.book_everywhere.common.auth.dto; -import com.book_everywhere.auth.entity.Role; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.user.OAuth2User; diff --git a/src/main/java/com/book_everywhere/auth/dto/OAuthAttributes.java b/src/main/java/com/book_everywhere/common/auth/dto/OAuthAttributes.java similarity index 90% rename from src/main/java/com/book_everywhere/auth/dto/OAuthAttributes.java rename to src/main/java/com/book_everywhere/common/auth/dto/OAuthAttributes.java index 1932533..8c48f32 100644 --- a/src/main/java/com/book_everywhere/auth/dto/OAuthAttributes.java +++ b/src/main/java/com/book_everywhere/common/auth/dto/OAuthAttributes.java @@ -1,7 +1,7 @@ -package com.book_everywhere.auth.dto; +package com.book_everywhere.common.auth.dto; -import com.book_everywhere.auth.entity.Role; -import com.book_everywhere.auth.entity.User; +import com.book_everywhere.common.auth.entity.Role; +import com.book_everywhere.common.auth.entity.User; import lombok.Builder; import lombok.Getter; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/com/book_everywhere/auth/dto/UserDto.java b/src/main/java/com/book_everywhere/common/auth/dto/UserDto.java similarity index 70% rename from src/main/java/com/book_everywhere/auth/dto/UserDto.java rename to src/main/java/com/book_everywhere/common/auth/dto/UserDto.java index 0a9c152..f9ee618 100644 --- a/src/main/java/com/book_everywhere/auth/dto/UserDto.java +++ b/src/main/java/com/book_everywhere/common/auth/dto/UserDto.java @@ -1,4 +1,4 @@ -package com.book_everywhere.auth.dto; +package com.book_everywhere.common.auth.dto; import lombok.Data; diff --git a/src/main/java/com/book_everywhere/auth/entity/Role.java b/src/main/java/com/book_everywhere/common/auth/entity/Role.java similarity index 50% rename from src/main/java/com/book_everywhere/auth/entity/Role.java rename to src/main/java/com/book_everywhere/common/auth/entity/Role.java index 3c1fa9a..65e415d 100644 --- a/src/main/java/com/book_everywhere/auth/entity/Role.java +++ b/src/main/java/com/book_everywhere/common/auth/entity/Role.java @@ -1,4 +1,4 @@ -package com.book_everywhere.auth.entity; +package com.book_everywhere.common.auth.entity; public enum Role { ROLE_ADMIN,ROLE_MEMBER diff --git a/src/main/java/com/book_everywhere/auth/entity/User.java b/src/main/java/com/book_everywhere/common/auth/entity/User.java similarity index 83% rename from src/main/java/com/book_everywhere/auth/entity/User.java rename to src/main/java/com/book_everywhere/common/auth/entity/User.java index 7e9c658..bbe2bf0 100644 --- a/src/main/java/com/book_everywhere/auth/entity/User.java +++ b/src/main/java/com/book_everywhere/common/auth/entity/User.java @@ -1,14 +1,12 @@ -package com.book_everywhere.auth.entity; +package com.book_everywhere.common.auth.entity; import com.book_everywhere.common.entity.BaseTimeEntity; -import com.book_everywhere.review.entity.Review; -import com.book_everywhere.tag.entity.Tagged; -import com.book_everywhere.pin.entity.Visit; +import com.book_everywhere.domain.review.entity.Review; +import com.book_everywhere.domain.tag.entity.Tagged; +import com.book_everywhere.domain.pin.entity.Visit; import jakarta.persistence.*; import lombok.*; -import org.hibernate.annotations.CreationTimestamp; -import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/com/book_everywhere/auth/repository/UserRepository.java b/src/main/java/com/book_everywhere/common/auth/repository/UserRepository.java similarity index 75% rename from src/main/java/com/book_everywhere/auth/repository/UserRepository.java rename to src/main/java/com/book_everywhere/common/auth/repository/UserRepository.java index 01a4684..b9818fa 100644 --- a/src/main/java/com/book_everywhere/auth/repository/UserRepository.java +++ b/src/main/java/com/book_everywhere/common/auth/repository/UserRepository.java @@ -1,6 +1,6 @@ -package com.book_everywhere.auth.repository; +package com.book_everywhere.common.auth.repository; -import com.book_everywhere.auth.entity.User; +import com.book_everywhere.common.auth.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; diff --git a/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java b/src/main/java/com/book_everywhere/common/auth/service/CustomOAuth2UserService.java similarity index 65% rename from src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java rename to src/main/java/com/book_everywhere/common/auth/service/CustomOAuth2UserService.java index f06a525..f35d789 100644 --- a/src/main/java/com/book_everywhere/auth/service/CustomOAuth2UserService.java +++ b/src/main/java/com/book_everywhere/common/auth/service/CustomOAuth2UserService.java @@ -1,32 +1,20 @@ -package com.book_everywhere.auth.service; - -import com.book_everywhere.auth.dto.CustomOAuth2User; -import com.book_everywhere.auth.dto.OAuthAttributes; -import com.book_everywhere.auth.dto.UserDto; -import com.book_everywhere.auth.entity.Role; -import com.book_everywhere.auth.entity.User; -import com.book_everywhere.auth.repository.UserRepository; +package com.book_everywhere.common.auth.service; + +import com.book_everywhere.common.auth.dto.CustomOAuth2User; +import com.book_everywhere.common.auth.dto.OAuthAttributes; +import com.book_everywhere.common.auth.dto.UserDto; +import com.book_everywhere.common.auth.entity.Role; +import com.book_everywhere.common.auth.entity.User; +import com.book_everywhere.common.auth.repository.UserRepository; import jakarta.servlet.http.HttpSession; 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.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; -import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; -import org.springframework.security.oauth2.core.user.DefaultOAuth2User; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.stereotype.Service; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; - @Service @RequiredArgsConstructor diff --git a/src/main/java/com/book_everywhere/exception/GlobalExceptionHandler.java b/src/main/java/com/book_everywhere/common/exception/GlobalExceptionHandler.java similarity index 77% rename from src/main/java/com/book_everywhere/exception/GlobalExceptionHandler.java rename to src/main/java/com/book_everywhere/common/exception/GlobalExceptionHandler.java index 51abee9..52ebcaf 100644 --- a/src/main/java/com/book_everywhere/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/book_everywhere/common/exception/GlobalExceptionHandler.java @@ -1,9 +1,9 @@ -package com.book_everywhere.exception; +package com.book_everywhere.common.exception; -import com.book_everywhere.exception.customs.CustomErrorCode; +import com.book_everywhere.common.exception.customs.CustomErrorCode; import com.book_everywhere.common.dto.CMRespDto; -import com.book_everywhere.exception.customs.CustomException; +import com.book_everywhere.common.exception.customs.CustomException; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; diff --git a/src/main/java/com/book_everywhere/exception/customs/CustomErrorCode.java b/src/main/java/com/book_everywhere/common/exception/customs/CustomErrorCode.java similarity index 95% rename from src/main/java/com/book_everywhere/exception/customs/CustomErrorCode.java rename to src/main/java/com/book_everywhere/common/exception/customs/CustomErrorCode.java index af6acba..1693773 100644 --- a/src/main/java/com/book_everywhere/exception/customs/CustomErrorCode.java +++ b/src/main/java/com/book_everywhere/common/exception/customs/CustomErrorCode.java @@ -1,4 +1,4 @@ -package com.book_everywhere.exception.customs; +package com.book_everywhere.common.exception.customs; import lombok.Getter; import org.springframework.http.HttpStatus; diff --git a/src/main/java/com/book_everywhere/exception/customs/CustomException.java b/src/main/java/com/book_everywhere/common/exception/customs/CustomException.java similarity index 83% rename from src/main/java/com/book_everywhere/exception/customs/CustomException.java rename to src/main/java/com/book_everywhere/common/exception/customs/CustomException.java index 8e4e493..20c365c 100644 --- a/src/main/java/com/book_everywhere/exception/customs/CustomException.java +++ b/src/main/java/com/book_everywhere/common/exception/customs/CustomException.java @@ -1,4 +1,4 @@ -package com.book_everywhere.exception.customs; +package com.book_everywhere.common.exception.customs; import lombok.Getter; diff --git a/src/main/java/com/book_everywhere/exception/customs/EntityNotFoundException.java b/src/main/java/com/book_everywhere/common/exception/customs/EntityNotFoundException.java similarity index 75% rename from src/main/java/com/book_everywhere/exception/customs/EntityNotFoundException.java rename to src/main/java/com/book_everywhere/common/exception/customs/EntityNotFoundException.java index 0050827..01037bd 100644 --- a/src/main/java/com/book_everywhere/exception/customs/EntityNotFoundException.java +++ b/src/main/java/com/book_everywhere/common/exception/customs/EntityNotFoundException.java @@ -1,4 +1,4 @@ -package com.book_everywhere.exception.customs; +package com.book_everywhere.common.exception.customs; public class EntityNotFoundException extends CustomException { public EntityNotFoundException(CustomErrorCode errorCode) { diff --git a/src/main/java/com/book_everywhere/exception/customs/PropertyBadRequestException.java b/src/main/java/com/book_everywhere/common/exception/customs/PropertyBadRequestException.java similarity index 75% rename from src/main/java/com/book_everywhere/exception/customs/PropertyBadRequestException.java rename to src/main/java/com/book_everywhere/common/exception/customs/PropertyBadRequestException.java index 0840605..b71ea66 100644 --- a/src/main/java/com/book_everywhere/exception/customs/PropertyBadRequestException.java +++ b/src/main/java/com/book_everywhere/common/exception/customs/PropertyBadRequestException.java @@ -1,4 +1,4 @@ -package com.book_everywhere.exception.customs; +package com.book_everywhere.common.exception.customs; public class PropertyBadRequestException extends CustomException{ public PropertyBadRequestException(CustomErrorCode errorCode) { diff --git a/src/main/java/com/book_everywhere/exception/customs/SQLException.java b/src/main/java/com/book_everywhere/common/exception/customs/SQLException.java similarity index 72% rename from src/main/java/com/book_everywhere/exception/customs/SQLException.java rename to src/main/java/com/book_everywhere/common/exception/customs/SQLException.java index 23f77ee..8b60ce1 100644 --- a/src/main/java/com/book_everywhere/exception/customs/SQLException.java +++ b/src/main/java/com/book_everywhere/common/exception/customs/SQLException.java @@ -1,4 +1,4 @@ -package com.book_everywhere.exception.customs; +package com.book_everywhere.common.exception.customs; public class SQLException extends CustomException{ public SQLException(CustomErrorCode errorCode) { diff --git a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java b/src/main/java/com/book_everywhere/common/jwt/filter/CustomSuccessHandler.java similarity index 90% rename from src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java rename to src/main/java/com/book_everywhere/common/jwt/filter/CustomSuccessHandler.java index 9602ff7..cf7903f 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/CustomSuccessHandler.java +++ b/src/main/java/com/book_everywhere/common/jwt/filter/CustomSuccessHandler.java @@ -1,7 +1,7 @@ -package com.book_everywhere.jwt.filter; +package com.book_everywhere.common.jwt.filter; -import com.book_everywhere.auth.dto.CustomOAuth2User; -import com.book_everywhere.jwt.token.JwtProvider; +import com.book_everywhere.common.auth.dto.CustomOAuth2User; +import com.book_everywhere.common.jwt.token.JwtProvider; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; diff --git a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/common/jwt/filter/JwtFilter.java similarity index 93% rename from src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java rename to src/main/java/com/book_everywhere/common/jwt/filter/JwtFilter.java index 2f47743..39b60e4 100644 --- a/src/main/java/com/book_everywhere/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/common/jwt/filter/JwtFilter.java @@ -1,8 +1,8 @@ -package com.book_everywhere.jwt.filter; +package com.book_everywhere.common.jwt.filter; -import com.book_everywhere.auth.dto.CustomOAuth2User; -import com.book_everywhere.auth.dto.UserDto; -import com.book_everywhere.jwt.token.JwtProvider; +import com.book_everywhere.common.auth.dto.CustomOAuth2User; +import com.book_everywhere.common.auth.dto.UserDto; +import com.book_everywhere.common.jwt.token.JwtProvider; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; diff --git a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java b/src/main/java/com/book_everywhere/common/jwt/token/JwtProvider.java similarity index 97% rename from src/main/java/com/book_everywhere/jwt/token/JwtProvider.java rename to src/main/java/com/book_everywhere/common/jwt/token/JwtProvider.java index fc05ed5..315adae 100644 --- a/src/main/java/com/book_everywhere/jwt/token/JwtProvider.java +++ b/src/main/java/com/book_everywhere/common/jwt/token/JwtProvider.java @@ -1,4 +1,4 @@ -package com.book_everywhere.jwt.token; +package com.book_everywhere.common.jwt.token; import io.jsonwebtoken.*; import jakarta.servlet.http.Cookie; diff --git a/src/main/java/com/book_everywhere/redis/RedisConfig.java b/src/main/java/com/book_everywhere/common/redis/RedisConfig.java similarity index 97% rename from src/main/java/com/book_everywhere/redis/RedisConfig.java rename to src/main/java/com/book_everywhere/common/redis/RedisConfig.java index 0554d92..0c50197 100644 --- a/src/main/java/com/book_everywhere/redis/RedisConfig.java +++ b/src/main/java/com/book_everywhere/common/redis/RedisConfig.java @@ -1,4 +1,4 @@ -package com.book_everywhere.redis; +package com.book_everywhere.common.redis; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; diff --git a/src/main/java/com/book_everywhere/redis/RedisService.java b/src/main/java/com/book_everywhere/common/redis/RedisService.java similarity index 98% rename from src/main/java/com/book_everywhere/redis/RedisService.java rename to src/main/java/com/book_everywhere/common/redis/RedisService.java index 1ddf5cc..046c6ee 100644 --- a/src/main/java/com/book_everywhere/redis/RedisService.java +++ b/src/main/java/com/book_everywhere/common/redis/RedisService.java @@ -1,4 +1,4 @@ -package com.book_everywhere.redis; +package com.book_everywhere.common.redis; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; diff --git a/src/main/java/com/book_everywhere/swagger/SwaggerConfig.java b/src/main/java/com/book_everywhere/common/swagger/SwaggerConfig.java similarity index 95% rename from src/main/java/com/book_everywhere/swagger/SwaggerConfig.java rename to src/main/java/com/book_everywhere/common/swagger/SwaggerConfig.java index 59d7875..d727d2d 100644 --- a/src/main/java/com/book_everywhere/swagger/SwaggerConfig.java +++ b/src/main/java/com/book_everywhere/common/swagger/SwaggerConfig.java @@ -1,4 +1,4 @@ -package com.book_everywhere.swagger; +package com.book_everywhere.common.swagger; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; diff --git a/src/main/java/com/book_everywhere/book/controller/BookController.java b/src/main/java/com/book_everywhere/domain/book/controller/BookController.java similarity index 88% rename from src/main/java/com/book_everywhere/book/controller/BookController.java rename to src/main/java/com/book_everywhere/domain/book/controller/BookController.java index 680caf2..181a03b 100644 --- a/src/main/java/com/book_everywhere/book/controller/BookController.java +++ b/src/main/java/com/book_everywhere/domain/book/controller/BookController.java @@ -1,9 +1,9 @@ -package com.book_everywhere.book.controller; +package com.book_everywhere.domain.book.controller; -import com.book_everywhere.book.service.BookService; +import com.book_everywhere.domain.book.service.BookService; import com.book_everywhere.common.dto.CMRespDto; -import com.book_everywhere.book.dto.BookDto; +import com.book_everywhere.domain.book.dto.BookDto; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; diff --git a/src/main/java/com/book_everywhere/book/dto/BookDocumentDto.java b/src/main/java/com/book_everywhere/domain/book/dto/BookDocumentDto.java similarity index 85% rename from src/main/java/com/book_everywhere/book/dto/BookDocumentDto.java rename to src/main/java/com/book_everywhere/domain/book/dto/BookDocumentDto.java index 5c9e282..6733c7e 100644 --- a/src/main/java/com/book_everywhere/book/dto/BookDocumentDto.java +++ b/src/main/java/com/book_everywhere/domain/book/dto/BookDocumentDto.java @@ -1,4 +1,4 @@ -package com.book_everywhere.book.dto; +package com.book_everywhere.domain.book.dto; import lombok.Data; diff --git a/src/main/java/com/book_everywhere/book/dto/BookDto.java b/src/main/java/com/book_everywhere/domain/book/dto/BookDto.java similarity index 81% rename from src/main/java/com/book_everywhere/book/dto/BookDto.java rename to src/main/java/com/book_everywhere/domain/book/dto/BookDto.java index 6fb6767..202c085 100644 --- a/src/main/java/com/book_everywhere/book/dto/BookDto.java +++ b/src/main/java/com/book_everywhere/domain/book/dto/BookDto.java @@ -1,10 +1,9 @@ -package com.book_everywhere.book.dto; +package com.book_everywhere.domain.book.dto; -import com.book_everywhere.book.entity.Book; +import com.book_everywhere.domain.book.entity.Book; import lombok.AllArgsConstructor; import lombok.Data; -import java.sql.Timestamp; import java.time.LocalDateTime; @Data diff --git a/src/main/java/com/book_everywhere/book/dto/BookRespDto.java b/src/main/java/com/book_everywhere/domain/book/dto/BookRespDto.java similarity index 78% rename from src/main/java/com/book_everywhere/book/dto/BookRespDto.java rename to src/main/java/com/book_everywhere/domain/book/dto/BookRespDto.java index 764246a..558c567 100644 --- a/src/main/java/com/book_everywhere/book/dto/BookRespDto.java +++ b/src/main/java/com/book_everywhere/domain/book/dto/BookRespDto.java @@ -1,7 +1,6 @@ -package com.book_everywhere.book.dto; +package com.book_everywhere.domain.book.dto; -import com.book_everywhere.book.entity.Book; -import com.book_everywhere.auth.entity.User; +import com.book_everywhere.domain.book.entity.Book; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/book_everywhere/book/entity/Book.java b/src/main/java/com/book_everywhere/domain/book/entity/Book.java similarity index 87% rename from src/main/java/com/book_everywhere/book/entity/Book.java rename to src/main/java/com/book_everywhere/domain/book/entity/Book.java index cf58c4a..04adb5f 100644 --- a/src/main/java/com/book_everywhere/book/entity/Book.java +++ b/src/main/java/com/book_everywhere/domain/book/entity/Book.java @@ -1,7 +1,7 @@ -package com.book_everywhere.book.entity; +package com.book_everywhere.domain.book.entity; import com.book_everywhere.common.entity.BaseTimeEntity; -import com.book_everywhere.review.entity.Review; +import com.book_everywhere.domain.review.entity.Review; import jakarta.persistence.*; import lombok.*; diff --git a/src/main/java/com/book_everywhere/book/repository/BookRepository.java b/src/main/java/com/book_everywhere/domain/book/repository/BookRepository.java similarity index 84% rename from src/main/java/com/book_everywhere/book/repository/BookRepository.java rename to src/main/java/com/book_everywhere/domain/book/repository/BookRepository.java index 57961e8..8a345fa 100644 --- a/src/main/java/com/book_everywhere/book/repository/BookRepository.java +++ b/src/main/java/com/book_everywhere/domain/book/repository/BookRepository.java @@ -1,10 +1,9 @@ -package com.book_everywhere.book.repository; +package com.book_everywhere.domain.book.repository; -import com.book_everywhere.book.entity.Book; +import com.book_everywhere.domain.book.entity.Book; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; import java.util.List; diff --git a/src/main/java/com/book_everywhere/book/service/BookService.java b/src/main/java/com/book_everywhere/domain/book/service/BookService.java similarity index 59% rename from src/main/java/com/book_everywhere/book/service/BookService.java rename to src/main/java/com/book_everywhere/domain/book/service/BookService.java index 7d775cf..21408aa 100644 --- a/src/main/java/com/book_everywhere/book/service/BookService.java +++ b/src/main/java/com/book_everywhere/domain/book/service/BookService.java @@ -1,7 +1,7 @@ -package com.book_everywhere.book.service; +package com.book_everywhere.domain.book.service; -import com.book_everywhere.book.dto.BookDto; -import com.book_everywhere.review.dto.ReviewRespDto; +import com.book_everywhere.domain.book.dto.BookDto; +import com.book_everywhere.domain.review.dto.ReviewRespDto; import java.util.List; diff --git a/src/main/java/com/book_everywhere/book/service/BookServiceImpl.java b/src/main/java/com/book_everywhere/domain/book/service/BookServiceImpl.java similarity index 76% rename from src/main/java/com/book_everywhere/book/service/BookServiceImpl.java rename to src/main/java/com/book_everywhere/domain/book/service/BookServiceImpl.java index e2da2bb..87c470e 100644 --- a/src/main/java/com/book_everywhere/book/service/BookServiceImpl.java +++ b/src/main/java/com/book_everywhere/domain/book/service/BookServiceImpl.java @@ -1,12 +1,12 @@ -package com.book_everywhere.book.service; - -import com.book_everywhere.book.entity.Book; -import com.book_everywhere.book.repository.BookRepository; -import com.book_everywhere.book.dto.BookDto; -import com.book_everywhere.book.dto.BookRespDto; -import com.book_everywhere.review.dto.ReviewRespDto; -import com.book_everywhere.exception.customs.CustomErrorCode; -import com.book_everywhere.exception.customs.EntityNotFoundException; +package com.book_everywhere.domain.book.service; + +import com.book_everywhere.domain.book.entity.Book; +import com.book_everywhere.domain.book.repository.BookRepository; +import com.book_everywhere.domain.book.dto.BookDto; +import com.book_everywhere.domain.book.dto.BookRespDto; +import com.book_everywhere.domain.review.dto.ReviewRespDto; +import com.book_everywhere.common.exception.customs.CustomErrorCode; +import com.book_everywhere.common.exception.customs.EntityNotFoundException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/src/main/java/com/book_everywhere/data/controller/DataController.java b/src/main/java/com/book_everywhere/domain/data/controller/DataController.java similarity index 86% rename from src/main/java/com/book_everywhere/data/controller/DataController.java rename to src/main/java/com/book_everywhere/domain/data/controller/DataController.java index f7bd5a5..894b2a4 100644 --- a/src/main/java/com/book_everywhere/data/controller/DataController.java +++ b/src/main/java/com/book_everywhere/domain/data/controller/DataController.java @@ -1,7 +1,7 @@ -package com.book_everywhere.data.controller; +package com.book_everywhere.domain.data.controller; -import com.book_everywhere.data.service.DataService; -import com.book_everywhere.data.dto.AllDataDto; +import com.book_everywhere.domain.data.dto.AllDataDto; +import com.book_everywhere.domain.data.service.DataService; import com.book_everywhere.common.dto.CMRespDto; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; diff --git a/src/main/java/com/book_everywhere/data/dto/AllDataDto.java b/src/main/java/com/book_everywhere/domain/data/dto/AllDataDto.java similarity index 71% rename from src/main/java/com/book_everywhere/data/dto/AllDataDto.java rename to src/main/java/com/book_everywhere/domain/data/dto/AllDataDto.java index 47b07e5..539cad6 100644 --- a/src/main/java/com/book_everywhere/data/dto/AllDataDto.java +++ b/src/main/java/com/book_everywhere/domain/data/dto/AllDataDto.java @@ -1,11 +1,10 @@ -package com.book_everywhere.data.dto; -import com.book_everywhere.book.dto.BookRespDto; -import com.book_everywhere.pin.dto.PinRespDto; -import com.book_everywhere.tag.dto.TagRespDto; +package com.book_everywhere.domain.data.dto; +import com.book_everywhere.domain.book.dto.BookRespDto; +import com.book_everywhere.domain.pin.dto.PinRespDto; +import com.book_everywhere.domain.tag.dto.TagRespDto; import lombok.AllArgsConstructor; import lombok.Data; -import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.List; diff --git a/src/main/java/com/book_everywhere/data/service/DataService.java b/src/main/java/com/book_everywhere/domain/data/service/DataService.java similarity index 82% rename from src/main/java/com/book_everywhere/data/service/DataService.java rename to src/main/java/com/book_everywhere/domain/data/service/DataService.java index de4b20e..ec73436 100644 --- a/src/main/java/com/book_everywhere/data/service/DataService.java +++ b/src/main/java/com/book_everywhere/domain/data/service/DataService.java @@ -1,23 +1,23 @@ -package com.book_everywhere.data.service; - -import com.book_everywhere.book.entity.Book; -import com.book_everywhere.book.repository.BookRepository; -import com.book_everywhere.data.dto.AllDataDto; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.pin.repository.PinRepository; -import com.book_everywhere.review.entity.Review; -import com.book_everywhere.review.repository.ReviewRepository; -import com.book_everywhere.tag.entity.Tag; -import com.book_everywhere.tag.repository.TagRepository; -import com.book_everywhere.tag.entity.Tagged; -import com.book_everywhere.tag.repository.TaggedRepository; -import com.book_everywhere.pin.entity.Visit; -import com.book_everywhere.pin.repository.VisitRepository; -import com.book_everywhere.book.dto.BookRespDto; -import com.book_everywhere.pin.dto.PinRespDto; -import com.book_everywhere.tag.dto.TagRespDto; -import com.book_everywhere.exception.customs.CustomErrorCode; -import com.book_everywhere.exception.customs.EntityNotFoundException; +package com.book_everywhere.domain.data.service; + +import com.book_everywhere.domain.book.entity.Book; +import com.book_everywhere.domain.book.repository.BookRepository; +import com.book_everywhere.domain.data.dto.AllDataDto; +import com.book_everywhere.domain.pin.entity.Pin; +import com.book_everywhere.domain.pin.repository.PinRepository; +import com.book_everywhere.domain.review.entity.Review; +import com.book_everywhere.domain.review.repository.ReviewRepository; +import com.book_everywhere.domain.tag.entity.Tag; +import com.book_everywhere.domain.tag.repository.TagRepository; +import com.book_everywhere.domain.tag.entity.Tagged; +import com.book_everywhere.domain.tag.repository.TaggedRepository; +import com.book_everywhere.domain.pin.entity.Visit; +import com.book_everywhere.domain.pin.repository.VisitRepository; +import com.book_everywhere.domain.book.dto.BookRespDto; +import com.book_everywhere.domain.pin.dto.PinRespDto; +import com.book_everywhere.domain.tag.dto.TagRespDto; +import com.book_everywhere.common.exception.customs.CustomErrorCode; +import com.book_everywhere.common.exception.customs.EntityNotFoundException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/src/main/java/com/book_everywhere/likes/entity/Likes.java b/src/main/java/com/book_everywhere/domain/likes/entity/Likes.java similarity index 85% rename from src/main/java/com/book_everywhere/likes/entity/Likes.java rename to src/main/java/com/book_everywhere/domain/likes/entity/Likes.java index a87f417..122b5e7 100644 --- a/src/main/java/com/book_everywhere/likes/entity/Likes.java +++ b/src/main/java/com/book_everywhere/domain/likes/entity/Likes.java @@ -1,8 +1,8 @@ -package com.book_everywhere.likes.entity; +package com.book_everywhere.domain.likes.entity; -import com.book_everywhere.auth.entity.User; +import com.book_everywhere.common.auth.entity.User; import com.book_everywhere.common.entity.BaseTimeEntity; -import com.book_everywhere.review.entity.Review; +import com.book_everywhere.domain.review.entity.Review; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import jakarta.persistence.*; import lombok.AllArgsConstructor; diff --git a/src/main/java/com/book_everywhere/likes/repository/LikesRepository.java b/src/main/java/com/book_everywhere/domain/likes/repository/LikesRepository.java similarity index 88% rename from src/main/java/com/book_everywhere/likes/repository/LikesRepository.java rename to src/main/java/com/book_everywhere/domain/likes/repository/LikesRepository.java index 6c2c59e..aaafbc9 100644 --- a/src/main/java/com/book_everywhere/likes/repository/LikesRepository.java +++ b/src/main/java/com/book_everywhere/domain/likes/repository/LikesRepository.java @@ -1,6 +1,6 @@ -package com.book_everywhere.likes.repository; +package com.book_everywhere.domain.likes.repository; -import com.book_everywhere.likes.entity.Likes; +import com.book_everywhere.domain.likes.entity.Likes; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; diff --git a/src/main/java/com/book_everywhere/likes/service/LikesCachingService.java b/src/main/java/com/book_everywhere/domain/likes/service/LikesCachingService.java similarity index 74% rename from src/main/java/com/book_everywhere/likes/service/LikesCachingService.java rename to src/main/java/com/book_everywhere/domain/likes/service/LikesCachingService.java index 56ee641..2d6cc2d 100644 --- a/src/main/java/com/book_everywhere/likes/service/LikesCachingService.java +++ b/src/main/java/com/book_everywhere/domain/likes/service/LikesCachingService.java @@ -1,4 +1,4 @@ -package com.book_everywhere.likes.service; +package com.book_everywhere.domain.likes.service; public interface LikesCachingService { diff --git a/src/main/java/com/book_everywhere/likes/service/LikesCachingServiceImpl.java b/src/main/java/com/book_everywhere/domain/likes/service/LikesCachingServiceImpl.java similarity index 85% rename from src/main/java/com/book_everywhere/likes/service/LikesCachingServiceImpl.java rename to src/main/java/com/book_everywhere/domain/likes/service/LikesCachingServiceImpl.java index 9820e91..553c6be 100644 --- a/src/main/java/com/book_everywhere/likes/service/LikesCachingServiceImpl.java +++ b/src/main/java/com/book_everywhere/domain/likes/service/LikesCachingServiceImpl.java @@ -1,6 +1,6 @@ -package com.book_everywhere.likes.service; +package com.book_everywhere.domain.likes.service; -import com.book_everywhere.likes.repository.LikesRepository; +import com.book_everywhere.domain.likes.repository.LikesRepository; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; diff --git a/src/main/java/com/book_everywhere/likes/service/LikesService.java b/src/main/java/com/book_everywhere/domain/likes/service/LikesService.java similarity index 74% rename from src/main/java/com/book_everywhere/likes/service/LikesService.java rename to src/main/java/com/book_everywhere/domain/likes/service/LikesService.java index 7044d31..9a7ccc0 100644 --- a/src/main/java/com/book_everywhere/likes/service/LikesService.java +++ b/src/main/java/com/book_everywhere/domain/likes/service/LikesService.java @@ -1,4 +1,4 @@ -package com.book_everywhere.likes.service; +package com.book_everywhere.domain.likes.service; public interface LikesService { diff --git a/src/main/java/com/book_everywhere/likes/service/LikesServiceImpl.java b/src/main/java/com/book_everywhere/domain/likes/service/LikesServiceImpl.java similarity index 73% rename from src/main/java/com/book_everywhere/likes/service/LikesServiceImpl.java rename to src/main/java/com/book_everywhere/domain/likes/service/LikesServiceImpl.java index eba6068..e2595a5 100644 --- a/src/main/java/com/book_everywhere/likes/service/LikesServiceImpl.java +++ b/src/main/java/com/book_everywhere/domain/likes/service/LikesServiceImpl.java @@ -1,11 +1,8 @@ -package com.book_everywhere.likes.service; +package com.book_everywhere.domain.likes.service; -import com.book_everywhere.auth.entity.User; -import com.book_everywhere.auth.repository.UserRepository; -import com.book_everywhere.likes.entity.Likes; -import com.book_everywhere.likes.repository.LikesRepository; -import com.book_everywhere.review.entity.Review; -import com.book_everywhere.review.repository.ReviewRepository; +import com.book_everywhere.common.auth.entity.User; +import com.book_everywhere.common.auth.repository.UserRepository; +import com.book_everywhere.domain.likes.repository.LikesRepository; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/src/main/java/com/book_everywhere/pin/controller/PinController.java b/src/main/java/com/book_everywhere/domain/pin/controller/PinController.java similarity index 88% rename from src/main/java/com/book_everywhere/pin/controller/PinController.java rename to src/main/java/com/book_everywhere/domain/pin/controller/PinController.java index 9c2b8d8..503ebe4 100644 --- a/src/main/java/com/book_everywhere/pin/controller/PinController.java +++ b/src/main/java/com/book_everywhere/domain/pin/controller/PinController.java @@ -1,16 +1,14 @@ -package com.book_everywhere.pin.controller; +package com.book_everywhere.domain.pin.controller; -import com.book_everywhere.pin.service.PinService; -import com.book_everywhere.review.service.ReviewService; +import com.book_everywhere.domain.pin.dto.PinDto; +import com.book_everywhere.domain.pin.dto.PinWithTagCountRespDto; +import com.book_everywhere.domain.pin.service.PinService; +import com.book_everywhere.domain.review.service.ReviewService; import com.book_everywhere.common.dto.CMRespDto; -import com.book_everywhere.pin.dto.PinDto; -import com.book_everywhere.pin.dto.PinWithTagCountRespDto; -import com.book_everywhere.review.dto.ReviewDto; +import com.book_everywhere.domain.review.dto.ReviewDto; import io.swagger.v3.oas.annotations.Operation; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; -import org.springframework.security.core.annotation.AuthenticationPrincipal; -import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.web.bind.annotation.*; import java.util.List; diff --git a/src/main/java/com/book_everywhere/pin/dto/PinDto.java b/src/main/java/com/book_everywhere/domain/pin/dto/PinDto.java similarity index 85% rename from src/main/java/com/book_everywhere/pin/dto/PinDto.java rename to src/main/java/com/book_everywhere/domain/pin/dto/PinDto.java index 2c52988..e37aa7c 100644 --- a/src/main/java/com/book_everywhere/pin/dto/PinDto.java +++ b/src/main/java/com/book_everywhere/domain/pin/dto/PinDto.java @@ -1,11 +1,9 @@ -package com.book_everywhere.pin.dto; +package com.book_everywhere.domain.pin.dto; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.review.entity.Review; +import com.book_everywhere.domain.pin.entity.Pin; import lombok.AllArgsConstructor; import lombok.Data; -import java.sql.Timestamp; import java.time.LocalDateTime; diff --git a/src/main/java/com/book_everywhere/pin/dto/PinRespDto.java b/src/main/java/com/book_everywhere/domain/pin/dto/PinRespDto.java similarity index 86% rename from src/main/java/com/book_everywhere/pin/dto/PinRespDto.java rename to src/main/java/com/book_everywhere/domain/pin/dto/PinRespDto.java index bc20135..5e9524b 100644 --- a/src/main/java/com/book_everywhere/pin/dto/PinRespDto.java +++ b/src/main/java/com/book_everywhere/domain/pin/dto/PinRespDto.java @@ -1,6 +1,6 @@ -package com.book_everywhere.pin.dto; +package com.book_everywhere.domain.pin.dto; -import com.book_everywhere.pin.entity.Pin; +import com.book_everywhere.domain.pin.entity.Pin; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/book_everywhere/pin/dto/PinWithTagCountRespDto.java b/src/main/java/com/book_everywhere/domain/pin/dto/PinWithTagCountRespDto.java similarity index 85% rename from src/main/java/com/book_everywhere/pin/dto/PinWithTagCountRespDto.java rename to src/main/java/com/book_everywhere/domain/pin/dto/PinWithTagCountRespDto.java index 26d9da3..fce823c 100644 --- a/src/main/java/com/book_everywhere/pin/dto/PinWithTagCountRespDto.java +++ b/src/main/java/com/book_everywhere/domain/pin/dto/PinWithTagCountRespDto.java @@ -1,11 +1,10 @@ -package com.book_everywhere.pin.dto; +package com.book_everywhere.domain.pin.dto; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.tag.dto.TagCountRespDto; +import com.book_everywhere.domain.pin.entity.Pin; +import com.book_everywhere.domain.tag.dto.TagCountRespDto; import lombok.AllArgsConstructor; import lombok.Data; -import java.sql.Timestamp; import java.time.LocalDateTime; import java.util.List; diff --git a/src/main/java/com/book_everywhere/pin/dto/VisitRespDto.java b/src/main/java/com/book_everywhere/domain/pin/dto/VisitRespDto.java similarity index 84% rename from src/main/java/com/book_everywhere/pin/dto/VisitRespDto.java rename to src/main/java/com/book_everywhere/domain/pin/dto/VisitRespDto.java index 7810ea2..1cac569 100644 --- a/src/main/java/com/book_everywhere/pin/dto/VisitRespDto.java +++ b/src/main/java/com/book_everywhere/domain/pin/dto/VisitRespDto.java @@ -1,4 +1,4 @@ -package com.book_everywhere.pin.dto; +package com.book_everywhere.domain.pin.dto; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/book_everywhere/pin/entity/Pin.java b/src/main/java/com/book_everywhere/domain/pin/entity/Pin.java similarity index 88% rename from src/main/java/com/book_everywhere/pin/entity/Pin.java rename to src/main/java/com/book_everywhere/domain/pin/entity/Pin.java index c3a0e31..be7f1fc 100644 --- a/src/main/java/com/book_everywhere/pin/entity/Pin.java +++ b/src/main/java/com/book_everywhere/domain/pin/entity/Pin.java @@ -1,8 +1,8 @@ -package com.book_everywhere.pin.entity; +package com.book_everywhere.domain.pin.entity; import com.book_everywhere.common.entity.BaseTimeEntity; -import com.book_everywhere.review.entity.Review; -import com.book_everywhere.tag.entity.Tagged; +import com.book_everywhere.domain.review.entity.Review; +import com.book_everywhere.domain.tag.entity.Tagged; import jakarta.persistence.*; import lombok.*; diff --git a/src/main/java/com/book_everywhere/pin/entity/Visit.java b/src/main/java/com/book_everywhere/domain/pin/entity/Visit.java similarity index 92% rename from src/main/java/com/book_everywhere/pin/entity/Visit.java rename to src/main/java/com/book_everywhere/domain/pin/entity/Visit.java index 0dcf39e..e7c6bee 100644 --- a/src/main/java/com/book_everywhere/pin/entity/Visit.java +++ b/src/main/java/com/book_everywhere/domain/pin/entity/Visit.java @@ -1,6 +1,6 @@ -package com.book_everywhere.pin.entity; +package com.book_everywhere.domain.pin.entity; -import com.book_everywhere.auth.entity.User; +import com.book_everywhere.common.auth.entity.User; import com.book_everywhere.common.entity.BaseTimeEntity; import jakarta.persistence.*; import lombok.*; diff --git a/src/main/java/com/book_everywhere/pin/repository/PinRepository.java b/src/main/java/com/book_everywhere/domain/pin/repository/PinRepository.java similarity index 90% rename from src/main/java/com/book_everywhere/pin/repository/PinRepository.java rename to src/main/java/com/book_everywhere/domain/pin/repository/PinRepository.java index e41c8fd..d09a6ee 100644 --- a/src/main/java/com/book_everywhere/pin/repository/PinRepository.java +++ b/src/main/java/com/book_everywhere/domain/pin/repository/PinRepository.java @@ -1,10 +1,9 @@ -package com.book_everywhere.pin.repository; +package com.book_everywhere.domain.pin.repository; -import com.book_everywhere.pin.entity.Pin; +import com.book_everywhere.domain.pin.entity.Pin; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; import java.util.List; diff --git a/src/main/java/com/book_everywhere/pin/repository/VisitRepository.java b/src/main/java/com/book_everywhere/domain/pin/repository/VisitRepository.java similarity index 82% rename from src/main/java/com/book_everywhere/pin/repository/VisitRepository.java rename to src/main/java/com/book_everywhere/domain/pin/repository/VisitRepository.java index 6c80aaf..6cc077a 100644 --- a/src/main/java/com/book_everywhere/pin/repository/VisitRepository.java +++ b/src/main/java/com/book_everywhere/domain/pin/repository/VisitRepository.java @@ -1,10 +1,9 @@ -package com.book_everywhere.pin.repository; +package com.book_everywhere.domain.pin.repository; -import com.book_everywhere.pin.entity.Visit; +import com.book_everywhere.domain.pin.entity.Visit; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; import java.util.List; diff --git a/src/main/java/com/book_everywhere/pin/service/PinService.java b/src/main/java/com/book_everywhere/domain/pin/service/PinService.java similarity index 66% rename from src/main/java/com/book_everywhere/pin/service/PinService.java rename to src/main/java/com/book_everywhere/domain/pin/service/PinService.java index 98e2363..05596c0 100644 --- a/src/main/java/com/book_everywhere/pin/service/PinService.java +++ b/src/main/java/com/book_everywhere/domain/pin/service/PinService.java @@ -1,8 +1,8 @@ -package com.book_everywhere.pin.service; +package com.book_everywhere.domain.pin.service; -import com.book_everywhere.pin.dto.PinDto; -import com.book_everywhere.pin.dto.PinWithTagCountRespDto; -import com.book_everywhere.review.dto.ReviewRespDto; +import com.book_everywhere.domain.pin.dto.PinDto; +import com.book_everywhere.domain.pin.dto.PinWithTagCountRespDto; +import com.book_everywhere.domain.review.dto.ReviewRespDto; import java.util.List; diff --git a/src/main/java/com/book_everywhere/pin/service/PinServiceImpl.java b/src/main/java/com/book_everywhere/domain/pin/service/PinServiceImpl.java similarity index 80% rename from src/main/java/com/book_everywhere/pin/service/PinServiceImpl.java rename to src/main/java/com/book_everywhere/domain/pin/service/PinServiceImpl.java index 286915f..705cbda 100644 --- a/src/main/java/com/book_everywhere/pin/service/PinServiceImpl.java +++ b/src/main/java/com/book_everywhere/domain/pin/service/PinServiceImpl.java @@ -1,15 +1,15 @@ -package com.book_everywhere.pin.service; +package com.book_everywhere.domain.pin.service; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.pin.repository.PinRepository; -import com.book_everywhere.tag.repository.TaggedRepository; -import com.book_everywhere.pin.dto.PinDto; -import com.book_everywhere.pin.dto.PinRespDto; -import com.book_everywhere.pin.dto.PinWithTagCountRespDto; -import com.book_everywhere.review.dto.ReviewRespDto; -import com.book_everywhere.tag.dto.TagCountRespDto; -import com.book_everywhere.exception.customs.CustomErrorCode; -import com.book_everywhere.exception.customs.EntityNotFoundException; +import com.book_everywhere.domain.pin.entity.Pin; +import com.book_everywhere.domain.pin.repository.PinRepository; +import com.book_everywhere.domain.tag.repository.TaggedRepository; +import com.book_everywhere.domain.pin.dto.PinDto; +import com.book_everywhere.domain.pin.dto.PinRespDto; +import com.book_everywhere.domain.pin.dto.PinWithTagCountRespDto; +import com.book_everywhere.domain.review.dto.ReviewRespDto; +import com.book_everywhere.domain.tag.dto.TagCountRespDto; +import com.book_everywhere.common.exception.customs.CustomErrorCode; +import com.book_everywhere.common.exception.customs.EntityNotFoundException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/src/main/java/com/book_everywhere/pin/service/VisitService.java b/src/main/java/com/book_everywhere/domain/pin/service/VisitService.java similarity index 52% rename from src/main/java/com/book_everywhere/pin/service/VisitService.java rename to src/main/java/com/book_everywhere/domain/pin/service/VisitService.java index 130038c..0c577e4 100644 --- a/src/main/java/com/book_everywhere/pin/service/VisitService.java +++ b/src/main/java/com/book_everywhere/domain/pin/service/VisitService.java @@ -1,6 +1,6 @@ -package com.book_everywhere.pin.service; +package com.book_everywhere.domain.pin.service; -import com.book_everywhere.review.dto.ReviewRespDto; +import com.book_everywhere.domain.review.dto.ReviewRespDto; public interface VisitService { void 독후감쓰기전방문등록또는수정(ReviewRespDto reviewRespDto); diff --git a/src/main/java/com/book_everywhere/pin/service/VisitServiceImpl.java b/src/main/java/com/book_everywhere/domain/pin/service/VisitServiceImpl.java similarity index 69% rename from src/main/java/com/book_everywhere/pin/service/VisitServiceImpl.java rename to src/main/java/com/book_everywhere/domain/pin/service/VisitServiceImpl.java index ad04f88..f8b5434 100644 --- a/src/main/java/com/book_everywhere/pin/service/VisitServiceImpl.java +++ b/src/main/java/com/book_everywhere/domain/pin/service/VisitServiceImpl.java @@ -1,14 +1,14 @@ -package com.book_everywhere.pin.service; +package com.book_everywhere.domain.pin.service; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.pin.repository.PinRepository; -import com.book_everywhere.pin.repository.VisitRepository; -import com.book_everywhere.auth.entity.User; -import com.book_everywhere.auth.repository.UserRepository; -import com.book_everywhere.pin.entity.Visit; -import com.book_everywhere.review.dto.ReviewRespDto; -import com.book_everywhere.exception.customs.CustomErrorCode; -import com.book_everywhere.exception.customs.EntityNotFoundException; +import com.book_everywhere.domain.pin.entity.Pin; +import com.book_everywhere.domain.pin.repository.PinRepository; +import com.book_everywhere.domain.pin.repository.VisitRepository; +import com.book_everywhere.common.auth.entity.User; +import com.book_everywhere.common.auth.repository.UserRepository; +import com.book_everywhere.domain.pin.entity.Visit; +import com.book_everywhere.domain.review.dto.ReviewRespDto; +import com.book_everywhere.common.exception.customs.CustomErrorCode; +import com.book_everywhere.common.exception.customs.EntityNotFoundException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/src/main/java/com/book_everywhere/review/controller/ReviewController.java b/src/main/java/com/book_everywhere/domain/review/controller/ReviewController.java similarity index 91% rename from src/main/java/com/book_everywhere/review/controller/ReviewController.java rename to src/main/java/com/book_everywhere/domain/review/controller/ReviewController.java index 29c11d1..eb468df 100644 --- a/src/main/java/com/book_everywhere/review/controller/ReviewController.java +++ b/src/main/java/com/book_everywhere/domain/review/controller/ReviewController.java @@ -1,15 +1,15 @@ -package com.book_everywhere.review.controller; +package com.book_everywhere.domain.review.controller; -import com.book_everywhere.book.service.BookService; -import com.book_everywhere.likes.service.LikesService; -import com.book_everywhere.pin.service.PinService; -import com.book_everywhere.pin.service.VisitService; -import com.book_everywhere.review.service.ReviewService; -import com.book_everywhere.tag.service.TaggedService; +import com.book_everywhere.domain.book.service.BookService; +import com.book_everywhere.domain.likes.service.LikesService; +import com.book_everywhere.domain.pin.service.PinService; +import com.book_everywhere.domain.pin.service.VisitService; +import com.book_everywhere.domain.review.dto.ReviewDto; +import com.book_everywhere.domain.review.dto.ReviewRespDto; +import com.book_everywhere.domain.review.service.ReviewService; +import com.book_everywhere.domain.tag.service.TaggedService; import com.book_everywhere.common.dto.CMRespDto; -import com.book_everywhere.review.dto.ReviewDto; -import com.book_everywhere.review.dto.ReviewRespDto; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; @@ -17,8 +17,6 @@ import io.swagger.v3.oas.annotations.responses.ApiResponses; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; -import org.springframework.security.core.annotation.AuthenticationPrincipal; -import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.web.bind.annotation.*; import java.util.List; diff --git a/src/main/java/com/book_everywhere/review/dto/ReviewDto.java b/src/main/java/com/book_everywhere/domain/review/dto/ReviewDto.java similarity index 80% rename from src/main/java/com/book_everywhere/review/dto/ReviewDto.java rename to src/main/java/com/book_everywhere/domain/review/dto/ReviewDto.java index 57fc8f3..1980892 100644 --- a/src/main/java/com/book_everywhere/review/dto/ReviewDto.java +++ b/src/main/java/com/book_everywhere/domain/review/dto/ReviewDto.java @@ -1,12 +1,9 @@ -package com.book_everywhere.review.dto; +package com.book_everywhere.domain.review.dto; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.book.entity.Book; -import com.book_everywhere.review.entity.Review; +import com.book_everywhere.domain.review.entity.Review; import lombok.AllArgsConstructor; import lombok.Data; -import java.sql.Timestamp; import java.time.LocalDateTime; diff --git a/src/main/java/com/book_everywhere/review/dto/ReviewRespDto.java b/src/main/java/com/book_everywhere/domain/review/dto/ReviewRespDto.java similarity index 67% rename from src/main/java/com/book_everywhere/review/dto/ReviewRespDto.java rename to src/main/java/com/book_everywhere/domain/review/dto/ReviewRespDto.java index 5c20d00..4c17215 100644 --- a/src/main/java/com/book_everywhere/review/dto/ReviewRespDto.java +++ b/src/main/java/com/book_everywhere/domain/review/dto/ReviewRespDto.java @@ -1,12 +1,11 @@ -package com.book_everywhere.review.dto; +package com.book_everywhere.domain.review.dto; -import com.book_everywhere.book.dto.BookRespDto; -import com.book_everywhere.book.entity.Book; -import com.book_everywhere.auth.entity.User; -import com.book_everywhere.pin.dto.PinRespDto; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.review.entity.Review; -import jakarta.persistence.Transient; +import com.book_everywhere.domain.book.dto.BookRespDto; +import com.book_everywhere.domain.book.entity.Book; +import com.book_everywhere.common.auth.entity.User; +import com.book_everywhere.domain.pin.dto.PinRespDto; +import com.book_everywhere.domain.pin.entity.Pin; +import com.book_everywhere.domain.review.entity.Review; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/book_everywhere/review/entity/Review.java b/src/main/java/com/book_everywhere/domain/review/entity/Review.java similarity index 90% rename from src/main/java/com/book_everywhere/review/entity/Review.java rename to src/main/java/com/book_everywhere/domain/review/entity/Review.java index 642c532..41fd732 100644 --- a/src/main/java/com/book_everywhere/review/entity/Review.java +++ b/src/main/java/com/book_everywhere/domain/review/entity/Review.java @@ -1,9 +1,9 @@ -package com.book_everywhere.review.entity; +package com.book_everywhere.domain.review.entity; -import com.book_everywhere.auth.entity.User; -import com.book_everywhere.book.entity.Book; +import com.book_everywhere.common.auth.entity.User; +import com.book_everywhere.domain.book.entity.Book; import com.book_everywhere.common.entity.BaseTimeEntity; -import com.book_everywhere.pin.entity.Pin; +import com.book_everywhere.domain.pin.entity.Pin; import jakarta.persistence.*; import lombok.*; diff --git a/src/main/java/com/book_everywhere/review/repository/ReviewRepository.java b/src/main/java/com/book_everywhere/domain/review/repository/ReviewRepository.java similarity index 83% rename from src/main/java/com/book_everywhere/review/repository/ReviewRepository.java rename to src/main/java/com/book_everywhere/domain/review/repository/ReviewRepository.java index af7327e..3ebdda1 100644 --- a/src/main/java/com/book_everywhere/review/repository/ReviewRepository.java +++ b/src/main/java/com/book_everywhere/domain/review/repository/ReviewRepository.java @@ -1,12 +1,9 @@ -package com.book_everywhere.review.repository; +package com.book_everywhere.domain.review.repository; -import com.book_everywhere.review.entity.Review; -import org.springframework.data.domain.Pageable; +import com.book_everywhere.domain.review.entity.Review; import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; import java.util.List; diff --git a/src/main/java/com/book_everywhere/review/service/ReviewService.java b/src/main/java/com/book_everywhere/domain/review/service/ReviewService.java similarity index 81% rename from src/main/java/com/book_everywhere/review/service/ReviewService.java rename to src/main/java/com/book_everywhere/domain/review/service/ReviewService.java index 97d21d7..831800c 100644 --- a/src/main/java/com/book_everywhere/review/service/ReviewService.java +++ b/src/main/java/com/book_everywhere/domain/review/service/ReviewService.java @@ -1,8 +1,7 @@ -package com.book_everywhere.review.service; +package com.book_everywhere.domain.review.service; -import com.book_everywhere.review.dto.ReviewDto; -import com.book_everywhere.review.dto.ReviewRespDto; -import org.springframework.security.oauth2.core.user.OAuth2User; +import com.book_everywhere.domain.review.dto.ReviewDto; +import com.book_everywhere.domain.review.dto.ReviewRespDto; import java.util.List; diff --git a/src/main/java/com/book_everywhere/review/service/ReviewServiceImpl.java b/src/main/java/com/book_everywhere/domain/review/service/ReviewServiceImpl.java similarity index 90% rename from src/main/java/com/book_everywhere/review/service/ReviewServiceImpl.java rename to src/main/java/com/book_everywhere/domain/review/service/ReviewServiceImpl.java index ae3355e..ebfdee2 100644 --- a/src/main/java/com/book_everywhere/review/service/ReviewServiceImpl.java +++ b/src/main/java/com/book_everywhere/domain/review/service/ReviewServiceImpl.java @@ -1,21 +1,21 @@ -package com.book_everywhere.review.service; - -import com.book_everywhere.book.entity.Book; -import com.book_everywhere.book.repository.BookRepository; -import com.book_everywhere.likes.repository.LikesRepository; -import com.book_everywhere.likes.service.LikesCachingService; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.pin.repository.PinRepository; -import com.book_everywhere.review.entity.Review; -import com.book_everywhere.review.repository.ReviewRepository; -import com.book_everywhere.auth.entity.User; -import com.book_everywhere.auth.repository.UserRepository; -import com.book_everywhere.tag.service.TaggedService; -import com.book_everywhere.exception.customs.CustomErrorCode; -import com.book_everywhere.exception.customs.EntityNotFoundException; -import com.book_everywhere.review.dto.ReviewRespDto; -import com.book_everywhere.exception.customs.PropertyBadRequestException; -import com.book_everywhere.review.dto.ReviewDto; +package com.book_everywhere.domain.review.service; + +import com.book_everywhere.domain.book.entity.Book; +import com.book_everywhere.domain.book.repository.BookRepository; +import com.book_everywhere.domain.likes.repository.LikesRepository; +import com.book_everywhere.domain.likes.service.LikesCachingService; +import com.book_everywhere.domain.pin.entity.Pin; +import com.book_everywhere.domain.pin.repository.PinRepository; +import com.book_everywhere.domain.review.entity.Review; +import com.book_everywhere.domain.review.repository.ReviewRepository; +import com.book_everywhere.common.auth.entity.User; +import com.book_everywhere.common.auth.repository.UserRepository; +import com.book_everywhere.domain.tag.service.TaggedService; +import com.book_everywhere.common.exception.customs.CustomErrorCode; +import com.book_everywhere.common.exception.customs.EntityNotFoundException; +import com.book_everywhere.domain.review.dto.ReviewRespDto; +import com.book_everywhere.common.exception.customs.PropertyBadRequestException; +import com.book_everywhere.domain.review.dto.ReviewDto; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -52,7 +52,6 @@ public class ReviewServiceImpl implements ReviewService { throw new EntityNotFoundException(CustomErrorCode.PIN_NOT_FOUND); } - Review review = Review.builder() .book(book) .pin(pin) diff --git a/src/main/java/com/book_everywhere/tag/controller/TagController.java b/src/main/java/com/book_everywhere/domain/tag/controller/TagController.java similarity index 79% rename from src/main/java/com/book_everywhere/tag/controller/TagController.java rename to src/main/java/com/book_everywhere/domain/tag/controller/TagController.java index b512938..2aeae23 100644 --- a/src/main/java/com/book_everywhere/tag/controller/TagController.java +++ b/src/main/java/com/book_everywhere/domain/tag/controller/TagController.java @@ -1,8 +1,8 @@ -package com.book_everywhere.tag.controller; +package com.book_everywhere.domain.tag.controller; -import com.book_everywhere.tag.service.TaggedService; +import com.book_everywhere.domain.tag.dto.TagDto; +import com.book_everywhere.domain.tag.service.TaggedService; import com.book_everywhere.common.dto.CMRespDto; -import com.book_everywhere.tag.dto.TagDto; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; diff --git a/src/main/java/com/book_everywhere/tag/dto/TagCountRespDto.java b/src/main/java/com/book_everywhere/domain/tag/dto/TagCountRespDto.java similarity index 79% rename from src/main/java/com/book_everywhere/tag/dto/TagCountRespDto.java rename to src/main/java/com/book_everywhere/domain/tag/dto/TagCountRespDto.java index 61a696d..46c6142 100644 --- a/src/main/java/com/book_everywhere/tag/dto/TagCountRespDto.java +++ b/src/main/java/com/book_everywhere/domain/tag/dto/TagCountRespDto.java @@ -1,4 +1,4 @@ -package com.book_everywhere.tag.dto; +package com.book_everywhere.domain.tag.dto; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/book_everywhere/tag/dto/TagDto.java b/src/main/java/com/book_everywhere/domain/tag/dto/TagDto.java similarity index 81% rename from src/main/java/com/book_everywhere/tag/dto/TagDto.java rename to src/main/java/com/book_everywhere/domain/tag/dto/TagDto.java index 99bea60..b9e88f8 100644 --- a/src/main/java/com/book_everywhere/tag/dto/TagDto.java +++ b/src/main/java/com/book_everywhere/domain/tag/dto/TagDto.java @@ -1,4 +1,4 @@ -package com.book_everywhere.tag.dto; +package com.book_everywhere.domain.tag.dto; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/book_everywhere/tag/dto/TagRespDto.java b/src/main/java/com/book_everywhere/domain/tag/dto/TagRespDto.java similarity index 83% rename from src/main/java/com/book_everywhere/tag/dto/TagRespDto.java rename to src/main/java/com/book_everywhere/domain/tag/dto/TagRespDto.java index 2b533f8..24f570c 100644 --- a/src/main/java/com/book_everywhere/tag/dto/TagRespDto.java +++ b/src/main/java/com/book_everywhere/domain/tag/dto/TagRespDto.java @@ -1,4 +1,4 @@ -package com.book_everywhere.tag.dto; +package com.book_everywhere.domain.tag.dto; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/book_everywhere/tag/dto/TaggedDto.java b/src/main/java/com/book_everywhere/domain/tag/dto/TaggedDto.java similarity index 88% rename from src/main/java/com/book_everywhere/tag/dto/TaggedDto.java rename to src/main/java/com/book_everywhere/domain/tag/dto/TaggedDto.java index e35bbc5..0114adc 100644 --- a/src/main/java/com/book_everywhere/tag/dto/TaggedDto.java +++ b/src/main/java/com/book_everywhere/domain/tag/dto/TaggedDto.java @@ -1,4 +1,4 @@ -package com.book_everywhere.tag.dto; +package com.book_everywhere.domain.tag.dto; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/com/book_everywhere/tag/entity/Category.java b/src/main/java/com/book_everywhere/domain/tag/entity/Category.java similarity index 92% rename from src/main/java/com/book_everywhere/tag/entity/Category.java rename to src/main/java/com/book_everywhere/domain/tag/entity/Category.java index 37e5218..6f6979a 100644 --- a/src/main/java/com/book_everywhere/tag/entity/Category.java +++ b/src/main/java/com/book_everywhere/domain/tag/entity/Category.java @@ -1,4 +1,4 @@ -package com.book_everywhere.tag.entity; +package com.book_everywhere.domain.tag.entity; import com.book_everywhere.common.entity.BaseTimeEntity; import jakarta.persistence.*; diff --git a/src/main/java/com/book_everywhere/tag/entity/Tag.java b/src/main/java/com/book_everywhere/domain/tag/entity/Tag.java similarity index 93% rename from src/main/java/com/book_everywhere/tag/entity/Tag.java rename to src/main/java/com/book_everywhere/domain/tag/entity/Tag.java index 66aa1fb..3774d71 100644 --- a/src/main/java/com/book_everywhere/tag/entity/Tag.java +++ b/src/main/java/com/book_everywhere/domain/tag/entity/Tag.java @@ -1,4 +1,4 @@ -package com.book_everywhere.tag.entity; +package com.book_everywhere.domain.tag.entity; import com.book_everywhere.common.entity.BaseTimeEntity; import jakarta.persistence.*; diff --git a/src/main/java/com/book_everywhere/tag/entity/Tagged.java b/src/main/java/com/book_everywhere/domain/tag/entity/Tagged.java similarity index 89% rename from src/main/java/com/book_everywhere/tag/entity/Tagged.java rename to src/main/java/com/book_everywhere/domain/tag/entity/Tagged.java index db29276..1b647c9 100644 --- a/src/main/java/com/book_everywhere/tag/entity/Tagged.java +++ b/src/main/java/com/book_everywhere/domain/tag/entity/Tagged.java @@ -1,8 +1,8 @@ -package com.book_everywhere.tag.entity; +package com.book_everywhere.domain.tag.entity; import com.book_everywhere.common.entity.BaseTimeEntity; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.auth.entity.User; +import com.book_everywhere.domain.pin.entity.Pin; +import com.book_everywhere.common.auth.entity.User; import jakarta.persistence.*; import lombok.*; diff --git a/src/main/java/com/book_everywhere/tag/repository/CategoryRepository.java b/src/main/java/com/book_everywhere/domain/tag/repository/CategoryRepository.java similarity index 57% rename from src/main/java/com/book_everywhere/tag/repository/CategoryRepository.java rename to src/main/java/com/book_everywhere/domain/tag/repository/CategoryRepository.java index 36ca555..5ddf7e7 100644 --- a/src/main/java/com/book_everywhere/tag/repository/CategoryRepository.java +++ b/src/main/java/com/book_everywhere/domain/tag/repository/CategoryRepository.java @@ -1,6 +1,6 @@ -package com.book_everywhere.tag.repository; +package com.book_everywhere.domain.tag.repository; -import com.book_everywhere.tag.entity.Category; +import com.book_everywhere.domain.tag.entity.Category; import org.springframework.data.jpa.repository.JpaRepository; public interface CategoryRepository extends JpaRepository { diff --git a/src/main/java/com/book_everywhere/tag/repository/TagRepository.java b/src/main/java/com/book_everywhere/domain/tag/repository/TagRepository.java similarity index 74% rename from src/main/java/com/book_everywhere/tag/repository/TagRepository.java rename to src/main/java/com/book_everywhere/domain/tag/repository/TagRepository.java index 97509f4..06dfa55 100644 --- a/src/main/java/com/book_everywhere/tag/repository/TagRepository.java +++ b/src/main/java/com/book_everywhere/domain/tag/repository/TagRepository.java @@ -1,10 +1,9 @@ -package com.book_everywhere.tag.repository; +package com.book_everywhere.domain.tag.repository; -import com.book_everywhere.tag.entity.Tag; +import com.book_everywhere.domain.tag.entity.Tag; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; public interface TagRepository extends JpaRepository { diff --git a/src/main/java/com/book_everywhere/tag/repository/TaggedRepository.java b/src/main/java/com/book_everywhere/domain/tag/repository/TaggedRepository.java similarity index 85% rename from src/main/java/com/book_everywhere/tag/repository/TaggedRepository.java rename to src/main/java/com/book_everywhere/domain/tag/repository/TaggedRepository.java index 402eaf6..0fb9f05 100644 --- a/src/main/java/com/book_everywhere/tag/repository/TaggedRepository.java +++ b/src/main/java/com/book_everywhere/domain/tag/repository/TaggedRepository.java @@ -1,13 +1,10 @@ -package com.book_everywhere.tag.repository; +package com.book_everywhere.domain.tag.repository; -import com.book_everywhere.tag.entity.Tagged; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; +import com.book_everywhere.domain.tag.entity.Tagged; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; import java.util.List; diff --git a/src/main/java/com/book_everywhere/tag/service/TaggedService.java b/src/main/java/com/book_everywhere/domain/tag/service/TaggedService.java similarity index 56% rename from src/main/java/com/book_everywhere/tag/service/TaggedService.java rename to src/main/java/com/book_everywhere/domain/tag/service/TaggedService.java index 907dd5c..07450cf 100644 --- a/src/main/java/com/book_everywhere/tag/service/TaggedService.java +++ b/src/main/java/com/book_everywhere/domain/tag/service/TaggedService.java @@ -1,7 +1,7 @@ -package com.book_everywhere.tag.service; +package com.book_everywhere.domain.tag.service; -import com.book_everywhere.review.dto.ReviewRespDto; -import com.book_everywhere.tag.dto.TagDto; +import com.book_everywhere.domain.review.dto.ReviewRespDto; +import com.book_everywhere.domain.tag.dto.TagDto; import java.util.List; diff --git a/src/main/java/com/book_everywhere/tag/service/TaggedServiceImpl.java b/src/main/java/com/book_everywhere/domain/tag/service/TaggedServiceImpl.java similarity index 73% rename from src/main/java/com/book_everywhere/tag/service/TaggedServiceImpl.java rename to src/main/java/com/book_everywhere/domain/tag/service/TaggedServiceImpl.java index 1c2af15..95a6c1d 100644 --- a/src/main/java/com/book_everywhere/tag/service/TaggedServiceImpl.java +++ b/src/main/java/com/book_everywhere/domain/tag/service/TaggedServiceImpl.java @@ -1,17 +1,17 @@ -package com.book_everywhere.tag.service; +package com.book_everywhere.domain.tag.service; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.pin.repository.PinRepository; -import com.book_everywhere.tag.entity.Tag; -import com.book_everywhere.tag.repository.TagRepository; -import com.book_everywhere.tag.entity.Tagged; -import com.book_everywhere.tag.repository.TaggedRepository; -import com.book_everywhere.auth.entity.User; -import com.book_everywhere.auth.repository.UserRepository; -import com.book_everywhere.review.dto.ReviewRespDto; -import com.book_everywhere.tag.dto.TagDto; -import com.book_everywhere.exception.customs.CustomErrorCode; -import com.book_everywhere.exception.customs.EntityNotFoundException; +import com.book_everywhere.domain.pin.entity.Pin; +import com.book_everywhere.domain.pin.repository.PinRepository; +import com.book_everywhere.domain.tag.dto.TagDto; +import com.book_everywhere.domain.tag.entity.Tag; +import com.book_everywhere.domain.tag.repository.TagRepository; +import com.book_everywhere.domain.tag.entity.Tagged; +import com.book_everywhere.domain.tag.repository.TaggedRepository; +import com.book_everywhere.common.auth.entity.User; +import com.book_everywhere.common.auth.repository.UserRepository; +import com.book_everywhere.domain.review.dto.ReviewRespDto; +import com.book_everywhere.common.exception.customs.CustomErrorCode; +import com.book_everywhere.common.exception.customs.EntityNotFoundException; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; diff --git a/src/test/java/com/book_everywhere/domain/auth/UserTestBuilder.java b/src/test/java/com/book_everywhere/domain/auth/UserTestBuilder.java index 49f52c7..85262f6 100644 --- a/src/test/java/com/book_everywhere/domain/auth/UserTestBuilder.java +++ b/src/test/java/com/book_everywhere/domain/auth/UserTestBuilder.java @@ -1,8 +1,8 @@ package com.book_everywhere.domain.auth; -import com.book_everywhere.auth.entity.Role; -import com.book_everywhere.auth.entity.User; +import com.book_everywhere.common.auth.entity.Role; +import com.book_everywhere.common.auth.entity.User; import java.util.ArrayList; diff --git a/src/test/java/com/book_everywhere/domain/book/dto/BookRespDtoBuilder.java b/src/test/java/com/book_everywhere/domain/book/dto/BookRespDtoBuilder.java index c815046..889d5f6 100644 --- a/src/test/java/com/book_everywhere/domain/book/dto/BookRespDtoBuilder.java +++ b/src/test/java/com/book_everywhere/domain/book/dto/BookRespDtoBuilder.java @@ -1,7 +1,6 @@ package com.book_everywhere.domain.book.dto; -import com.book_everywhere.book.dto.BookRespDto; -import com.book_everywhere.book.entity.Book; +import com.book_everywhere.domain.book.entity.Book; public class BookRespDtoBuilder { diff --git a/src/test/java/com/book_everywhere/domain/book/repository/BookRepositoryTest.java b/src/test/java/com/book_everywhere/domain/book/repository/BookRepositoryTest.java index 09d0470..46fdd93 100644 --- a/src/test/java/com/book_everywhere/domain/book/repository/BookRepositoryTest.java +++ b/src/test/java/com/book_everywhere/domain/book/repository/BookRepositoryTest.java @@ -1,17 +1,16 @@ package com.book_everywhere.domain.book.repository; -import com.book_everywhere.auth.entity.User; -import com.book_everywhere.auth.repository.UserRepository; -import com.book_everywhere.book.entity.Book; -import com.book_everywhere.book.repository.BookRepository; +import com.book_everywhere.common.auth.entity.User; +import com.book_everywhere.common.auth.repository.UserRepository; +import com.book_everywhere.domain.book.entity.Book; import com.book_everywhere.domain.auth.UserTestBuilder; import com.book_everywhere.domain.book.dto.BookRespDtoBuilder; import com.book_everywhere.domain.pin.dto.PinRespDtoTestBuilder; import com.book_everywhere.domain.review.dto.ReviewRespDtoTestBuilder; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.pin.repository.PinRepository; -import com.book_everywhere.review.entity.Review; -import com.book_everywhere.review.repository.ReviewRepository; +import com.book_everywhere.domain.pin.entity.Pin; +import com.book_everywhere.domain.pin.repository.PinRepository; +import com.book_everywhere.domain.review.entity.Review; +import com.book_everywhere.domain.review.repository.ReviewRepository; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/com/book_everywhere/domain/likes/repository/LikesRepositoryTest.java b/src/test/java/com/book_everywhere/domain/likes/repository/LikesRepositoryTest.java index ea7827c..1fe4f18 100644 --- a/src/test/java/com/book_everywhere/domain/likes/repository/LikesRepositoryTest.java +++ b/src/test/java/com/book_everywhere/domain/likes/repository/LikesRepositoryTest.java @@ -1,18 +1,17 @@ package com.book_everywhere.domain.likes.repository; -import com.book_everywhere.auth.entity.User; -import com.book_everywhere.auth.repository.UserRepository; -import com.book_everywhere.book.entity.Book; -import com.book_everywhere.book.repository.BookRepository; +import com.book_everywhere.common.auth.entity.User; +import com.book_everywhere.common.auth.repository.UserRepository; +import com.book_everywhere.domain.book.entity.Book; +import com.book_everywhere.domain.book.repository.BookRepository; import com.book_everywhere.domain.auth.UserTestBuilder; import com.book_everywhere.domain.book.dto.BookRespDtoBuilder; import com.book_everywhere.domain.pin.dto.PinRespDtoTestBuilder; import com.book_everywhere.domain.review.dto.ReviewRespDtoTestBuilder; -import com.book_everywhere.likes.repository.LikesRepository; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.pin.repository.PinRepository; -import com.book_everywhere.review.entity.Review; -import com.book_everywhere.review.repository.ReviewRepository; +import com.book_everywhere.domain.pin.entity.Pin; +import com.book_everywhere.domain.pin.repository.PinRepository; +import com.book_everywhere.domain.review.entity.Review; +import com.book_everywhere.domain.review.repository.ReviewRepository; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/com/book_everywhere/domain/pin/dto/PinRespDtoTestBuilder.java b/src/test/java/com/book_everywhere/domain/pin/dto/PinRespDtoTestBuilder.java index a38678b..44d8c04 100644 --- a/src/test/java/com/book_everywhere/domain/pin/dto/PinRespDtoTestBuilder.java +++ b/src/test/java/com/book_everywhere/domain/pin/dto/PinRespDtoTestBuilder.java @@ -1,8 +1,6 @@ package com.book_everywhere.domain.pin.dto; -import com.book_everywhere.book.entity.Book; -import com.book_everywhere.pin.dto.PinRespDto; -import com.book_everywhere.pin.entity.Pin; +import com.book_everywhere.domain.pin.entity.Pin; public class PinRespDtoTestBuilder { public static PinRespDto createDefault() { diff --git a/src/test/java/com/book_everywhere/domain/pin/service/PinServiceTest.java b/src/test/java/com/book_everywhere/domain/pin/service/PinServiceTest.java index b58cb96..4c3d36e 100644 --- a/src/test/java/com/book_everywhere/domain/pin/service/PinServiceTest.java +++ b/src/test/java/com/book_everywhere/domain/pin/service/PinServiceTest.java @@ -1,15 +1,14 @@ package com.book_everywhere.domain.pin.service; -import com.book_everywhere.book.dto.BookRespDto; +import com.book_everywhere.domain.book.dto.BookRespDto; import com.book_everywhere.domain.book.dto.BookRespDtoBuilder; import com.book_everywhere.domain.pin.dto.PinRespDtoTestBuilder; import com.book_everywhere.domain.review.dto.ReviewRespDtoTestBuilder; -import com.book_everywhere.pin.dto.PinDto; -import com.book_everywhere.pin.dto.PinRespDto; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.pin.repository.PinRepository; -import com.book_everywhere.pin.service.PinServiceImpl; -import com.book_everywhere.review.dto.ReviewRespDto; +import com.book_everywhere.domain.pin.dto.PinDto; +import com.book_everywhere.domain.pin.dto.PinRespDto; +import com.book_everywhere.domain.pin.entity.Pin; +import com.book_everywhere.domain.pin.repository.PinRepository; +import com.book_everywhere.domain.review.dto.ReviewRespDto; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/com/book_everywhere/domain/redis/RedisCrudTest.java b/src/test/java/com/book_everywhere/domain/redis/RedisCrudTest.java index 259475d..aafadb4 100644 --- a/src/test/java/com/book_everywhere/domain/redis/RedisCrudTest.java +++ b/src/test/java/com/book_everywhere/domain/redis/RedisCrudTest.java @@ -1,6 +1,6 @@ package com.book_everywhere.domain.redis; -import com.book_everywhere.redis.RedisService; +import com.book_everywhere.common.redis.RedisService; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; diff --git a/src/test/java/com/book_everywhere/domain/review/dto/ReviewRespDtoTestBuilder.java b/src/test/java/com/book_everywhere/domain/review/dto/ReviewRespDtoTestBuilder.java index 84556b4..ac5c551 100644 --- a/src/test/java/com/book_everywhere/domain/review/dto/ReviewRespDtoTestBuilder.java +++ b/src/test/java/com/book_everywhere/domain/review/dto/ReviewRespDtoTestBuilder.java @@ -2,13 +2,12 @@ import com.book_everywhere.domain.book.dto.BookRespDtoBuilder; import com.book_everywhere.domain.pin.dto.PinRespDtoTestBuilder; -import com.book_everywhere.pin.entity.Pin; -import com.book_everywhere.book.entity.Book; -import com.book_everywhere.review.dto.ReviewRespDto; -import com.book_everywhere.book.dto.BookRespDto; -import com.book_everywhere.pin.dto.PinRespDto; -import com.book_everywhere.review.entity.Review; -import com.book_everywhere.auth.entity.User; +import com.book_everywhere.domain.pin.entity.Pin; +import com.book_everywhere.domain.book.entity.Book; +import com.book_everywhere.domain.book.dto.BookRespDto; +import com.book_everywhere.domain.pin.dto.PinRespDto; +import com.book_everywhere.domain.review.entity.Review; +import com.book_everywhere.common.auth.entity.User; import java.util.List; diff --git a/src/test/java/com/book_everywhere/domain/review/service/ReviewServiceTest.java b/src/test/java/com/book_everywhere/domain/review/service/ReviewServiceTest.java index 6f50d42..f0127ec 100644 --- a/src/test/java/com/book_everywhere/domain/review/service/ReviewServiceTest.java +++ b/src/test/java/com/book_everywhere/domain/review/service/ReviewServiceTest.java @@ -1,19 +1,18 @@ package com.book_everywhere.domain.review.service; -import com.book_everywhere.auth.entity.User; -import com.book_everywhere.auth.repository.UserRepository; -import com.book_everywhere.book.dto.BookRespDto; -import com.book_everywhere.book.repository.BookRepository; +import com.book_everywhere.common.auth.entity.User; +import com.book_everywhere.common.auth.repository.UserRepository; +import com.book_everywhere.domain.book.dto.BookRespDto; +import com.book_everywhere.domain.book.repository.BookRepository; import com.book_everywhere.domain.auth.UserTestBuilder; import com.book_everywhere.domain.book.dto.BookRespDtoBuilder; import com.book_everywhere.domain.pin.dto.PinRespDtoTestBuilder; import com.book_everywhere.domain.review.dto.ReviewRespDtoTestBuilder; -import com.book_everywhere.pin.dto.PinRespDto; -import com.book_everywhere.pin.repository.PinRepository; -import com.book_everywhere.review.dto.ReviewRespDto; -import com.book_everywhere.review.entity.Review; -import com.book_everywhere.review.repository.ReviewRepository; -import com.book_everywhere.review.service.ReviewServiceImpl; +import com.book_everywhere.domain.pin.dto.PinRespDto; +import com.book_everywhere.domain.pin.repository.PinRepository; +import com.book_everywhere.domain.review.dto.ReviewRespDto; +import com.book_everywhere.domain.review.entity.Review; +import com.book_everywhere.domain.review.repository.ReviewRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; From 3bc22a3aeed1316831c44f28155d64ec45e4cb78 Mon Sep 17 00:00:00 2001 From: dltjdgh0428 Date: Mon, 8 Apr 2024 21:38:25 +0900 Subject: [PATCH 51/51] =?UTF-8?q?feat:=20Redis=20=EB=8F=84=EC=9E=85?= =?UTF-8?q?=EC=9D=84=20=ED=86=B5=ED=95=9C=20=EC=A2=8B=EC=95=84=EC=9A=94=20?= =?UTF-8?q?=EC=BA=90=EC=8B=B1=20=EC=B2=98=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 2 +- .../common/auth/config/SecurityConfig.java | 3 +-- .../common/jwt/filter/JwtFilter.java | 15 --------------- .../likes/service/LikesCachingServiceImpl.java | 3 +-- .../review/controller/ReviewController.java | 9 ++++----- 5 files changed, 7 insertions(+), 25 deletions(-) diff --git a/build.gradle b/build.gradle index 858d25a..e3dab2b 100644 --- a/build.gradle +++ b/build.gradle @@ -48,7 +48,7 @@ dependencies { runtimeOnly 'com.h2database:h2' } -tasks.withType(JavaCompile) { +tasks.withType(JavaCompile).configureEach { options.compilerArgs += ['-parameters'] sourceCompatibility = '17' targetCompatibility = '17' diff --git a/src/main/java/com/book_everywhere/common/auth/config/SecurityConfig.java b/src/main/java/com/book_everywhere/common/auth/config/SecurityConfig.java index cdb1954..1d0582d 100644 --- a/src/main/java/com/book_everywhere/common/auth/config/SecurityConfig.java +++ b/src/main/java/com/book_everywhere/common/auth/config/SecurityConfig.java @@ -62,10 +62,9 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // .addFilterAfter(new JwtFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class) .addFilterAfter(new JwtFilter(jwtProvider), OAuth2LoginAuthenticationFilter.class) .authorizeHttpRequests((authorizeRequests) -> authorizeRequests - .requestMatchers("/").permitAll() // 테스트 관련 url - .requestMatchers("/api/**").permitAll() +// .requestMatchers("/api/**").permitAll() .requestMatchers("/health", "/env", "/test/**", "/swagger-ui/**").permitAll() .requestMatchers("/api/reviews").permitAll() // 비회원도 볼수있는 url diff --git a/src/main/java/com/book_everywhere/common/jwt/filter/JwtFilter.java b/src/main/java/com/book_everywhere/common/jwt/filter/JwtFilter.java index 39b60e4..550d2af 100644 --- a/src/main/java/com/book_everywhere/common/jwt/filter/JwtFilter.java +++ b/src/main/java/com/book_everywhere/common/jwt/filter/JwtFilter.java @@ -29,21 +29,6 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse String authorization = null; Cookie[] cookies = request.getCookies(); - StringBuilder message = new StringBuilder(); - message.append("Request Method: ").append(request.getMethod()) - .append(", URL: ").append(request.getRequestURL()); - - // 헤더 정보 로깅 - Collections.list(request.getHeaderNames()).forEach(headerName -> - message.append(", ").append(headerName).append(": ").append(request.getHeader(headerName)) - ); - - // 파라미터 정보 로깅 (선택적) - request.getParameterMap().forEach((key, value) -> - message.append(", ").append(key).append(": ").append(Arrays.toString(value)) - ); - - logger.info(message.toString()); if (cookies != null) { for (Cookie cookie : cookies) { logger.info(cookie.toString()); diff --git a/src/main/java/com/book_everywhere/domain/likes/service/LikesCachingServiceImpl.java b/src/main/java/com/book_everywhere/domain/likes/service/LikesCachingServiceImpl.java index 1ee94b6..8610eeb 100644 --- a/src/main/java/com/book_everywhere/domain/likes/service/LikesCachingServiceImpl.java +++ b/src/main/java/com/book_everywhere/domain/likes/service/LikesCachingServiceImpl.java @@ -5,7 +5,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.CacheEvict; -import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @@ -19,7 +18,7 @@ public class LikesCachingServiceImpl implements LikesCachingService { @Override @Cacheable(value = "likesCount", key = "#reviewId") public Long 좋아요캐시업데이트(Long reviewId) { - logger.info(reviewId+"의 캐시가 없데이트 되었습니다."); + logger.info(reviewId+"의 캐시가 업데이트 되었습니다."); return likesRepository.countByReviewId(reviewId); } diff --git a/src/main/java/com/book_everywhere/domain/review/controller/ReviewController.java b/src/main/java/com/book_everywhere/domain/review/controller/ReviewController.java index eb468df..6666a02 100644 --- a/src/main/java/com/book_everywhere/domain/review/controller/ReviewController.java +++ b/src/main/java/com/book_everywhere/domain/review/controller/ReviewController.java @@ -1,6 +1,5 @@ package com.book_everywhere.domain.review.controller; - import com.book_everywhere.domain.book.service.BookService; import com.book_everywhere.domain.likes.service.LikesService; import com.book_everywhere.domain.pin.service.PinService; @@ -58,21 +57,21 @@ public CMRespDto addReview(@RequestBody ReviewRespDto reviewRespDto) { //공개 독후감 조회 @Operation(summary = "모든 독후감 조회", description = "조건에 없이 모든 독후감을 조회합니다 return = List") @GetMapping("/api/reviews") - public CMRespDto publicReviews(@RequestParam Long socialId) { + public CMRespDto publicReviews(@RequestParam(value = "socialId") Long socialId) { List result = reviewService.모든독후감조회(socialId); return new CMRespDto<>(HttpStatus.OK, result, "전체 공유 독후감 조회"); } @Operation(summary = "모든 공유 독후감 조회", description = "공유 독후감을 조회합니다 return = List") @GetMapping("/api/review/public") - public CMRespDto findPublicReviews(@RequestParam Long socialId) { + public CMRespDto findPublicReviews(@RequestParam(value = "socialId") Long socialId) { List result = reviewService.모든공유독후감조회(socialId); return new CMRespDto<>(HttpStatus.OK, result, "모든 공유 독후감 조회 완료"); } @Operation(summary = "단일 책 독후감 조회", description = "단일 책 독후감을 조회합니다 return = List") @GetMapping("/api/detail/{bookId}") - public CMRespDto bookReviews(@RequestParam Long socialId, @PathVariable Long bookId) { + public CMRespDto bookReviews(@RequestParam(value = "socialId") Long socialId, @PathVariable Long bookId) { List result = reviewService.책에따른모든리뷰(socialId, bookId); return new CMRespDto<>(HttpStatus.OK, result, "책에 따른 전체 독후감 조회"); } @@ -80,7 +79,7 @@ public CMRespDto bookReviews(@RequestParam Long socialId, @PathVariable Long //수정 @Operation(summary = "단일 독후감 조회", description = "특정 독후감을 조회합니다 return = ReviewDto") @GetMapping("/api/review/{reviewId}") - public CMRespDto getReview(@RequestParam Long socialId, @PathVariable Long reviewId) { + public CMRespDto getReview(@RequestParam(value = "socialId") Long socialId, @PathVariable Long reviewId) { ReviewDto reviewDto = reviewService.단일독후감조회(socialId, reviewId); return new CMRespDto<>(HttpStatus.OK, reviewDto, "단일 독후감 조회"); }