From 9b2c422b3b206c8090c105c5ca28f3d49b5060cd Mon Sep 17 00:00:00 2001 From: Kim Seung-yeop Date: Mon, 19 Aug 2024 17:14:48 +0900 Subject: [PATCH] =?UTF-8?q?SCRUM-66=20fix:=20=EC=8B=9C=ED=81=90=EB=A6=AC?= =?UTF-8?q?=ED=8B=B0=20=EC=97=90=EB=9F=AC=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 12 +- .../golagola/config/SecurityConfig.java | 114 +++++------------- .../golagola/controller/MainController.java | 16 --- .../golagola/controller/MyController.java | 16 --- .../auth}/Repository/UserRepository.java | 4 +- .../auth}/dto/CustomOAuth2User.java | 2 +- .../{ => domain/auth}/dto/KakaoResponse.java | 2 +- .../{ => domain/auth}/dto/NaverResponse.java | 3 +- .../{ => domain/auth}/dto/OAuth2Response.java | 2 +- .../{ => domain/auth}/dto/UserDTO.java | 2 +- .../{ => domain/auth}/entity/UserEntity.java | 2 +- .../{ => security}/jwt/JWTFilter.java | 47 ++++---- .../golagola/{ => security}/jwt/JWTUtil.java | 4 +- .../oauth2/CustomSuccessHandler.java | 8 +- .../golagola/security/service/JwtService.java | 30 ++--- .../service/CustomOAuth2UserService.java | 6 +- src/main/resources/application.properties | 6 +- 17 files changed, 90 insertions(+), 186 deletions(-) delete mode 100644 src/main/java/com/kakaoteck/golagola/controller/MainController.java delete mode 100644 src/main/java/com/kakaoteck/golagola/controller/MyController.java rename src/main/java/com/kakaoteck/golagola/{ => domain/auth}/Repository/UserRepository.java (69%) rename src/main/java/com/kakaoteck/golagola/{ => domain/auth}/dto/CustomOAuth2User.java (95%) rename src/main/java/com/kakaoteck/golagola/{ => domain/auth}/dto/KakaoResponse.java (95%) rename src/main/java/com/kakaoteck/golagola/{ => domain/auth}/dto/NaverResponse.java (90%) rename src/main/java/com/kakaoteck/golagola/{ => domain/auth}/dto/OAuth2Response.java (85%) rename src/main/java/com/kakaoteck/golagola/{ => domain/auth}/dto/UserDTO.java (77%) rename src/main/java/com/kakaoteck/golagola/{ => domain/auth}/entity/UserEntity.java (89%) rename src/main/java/com/kakaoteck/golagola/{ => security}/jwt/JWTFilter.java (64%) rename src/main/java/com/kakaoteck/golagola/{ => security}/jwt/JWTUtil.java (97%) rename src/main/java/com/kakaoteck/golagola/{ => security}/oauth2/CustomSuccessHandler.java (89%) diff --git a/build.gradle b/build.gradle index 7263752..8e7e596 100644 --- a/build.gradle +++ b/build.gradle @@ -57,12 +57,12 @@ dependencies { // Mysql runtimeOnly('com.mysql:mysql-connector-j') - // Jwt - implementation 'io.jsonwebtoken:jjwt-api:0.11.5' - implementation 'io.jsonwebtoken:jjwt-impl:0.11.5' - implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5' - implementation 'commons-codec:commons-codec:1.13' - implementation 'com.auth0:java-jwt:3.13.0' +// // Jwt +// implementation 'io.jsonwebtoken:jjwt-api:0.11.5' +// implementation 'io.jsonwebtoken:jjwt-impl:0.11.5' +// implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5' +// implementation 'commons-codec:commons-codec:1.13' +// implementation 'com.auth0:java-jwt:3.13.0' // Redis implementation 'org.springframework.boot:spring-boot-starter-data-redis' diff --git a/src/main/java/com/kakaoteck/golagola/config/SecurityConfig.java b/src/main/java/com/kakaoteck/golagola/config/SecurityConfig.java index 6984021..96795c9 100644 --- a/src/main/java/com/kakaoteck/golagola/config/SecurityConfig.java +++ b/src/main/java/com/kakaoteck/golagola/config/SecurityConfig.java @@ -1,37 +1,29 @@ package com.kakaoteck.golagola.config; - -import com.kakaoteck.golagola.jwt.JWTFilter; -import com.kakaoteck.golagola.jwt.JWTUtil; -import com.kakaoteck.golagola.oauth2.CustomSuccessHandler; +import com.kakaoteck.golagola.security.filter.JwtAuthenticationFilter; +import com.kakaoteck.golagola.security.jwt.JWTFilter; +import com.kakaoteck.golagola.security.jwt.JWTUtil; +import com.kakaoteck.golagola.security.oauth2.CustomSuccessHandler; import com.kakaoteck.golagola.service.CustomOAuth2UserService; import jakarta.servlet.http.HttpServletRequest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.http.SessionCreationPolicy; 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.LogoutHandler; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import java.util.Collections; -import com.kakaoteck.golagola.security.filter.JwtAuthenticationFilter; import lombok.RequiredArgsConstructor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; -import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.security.web.authentication.logout.LogoutHandler; import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS; @@ -40,7 +32,7 @@ @Configuration @EnableWebSecurity public class SecurityConfig { - + private final CustomOAuth2UserService customOAuth2UserService; private final CustomSuccessHandler customSuccessHandler; private final JWTUtil jwtUtil; @@ -48,71 +40,53 @@ public class SecurityConfig { private final AuthenticationProvider authenticationProvider; private final LogoutHandler logoutHandler; - public SecurityConfig(CustomOAuth2UserService customOAuth2UserService, CustomSuccessHandler customSuccessHandler, JWTUtil jwtUtil) { - - this.customOAuth2UserService = customOAuth2UserService; - this.customSuccessHandler = customSuccessHandler; - this.jwtUtil = jwtUtil; - } - @Bean - public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ + public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.cors(corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() { - - @Override - public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { - - CorsConfiguration configuration = new CorsConfiguration(); - - configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000")); - configuration.setAllowedMethods(Collections.singletonList("*")); - configuration.setAllowCredentials(true); - configuration.setAllowedHeaders(Collections.singletonList("*")); - configuration.setMaxAge(3600L); - - configuration.setExposedHeaders(Collections.singletonList("Set-Cookie")); - configuration.setExposedHeaders(Collections.singletonList("Authorization")); - - return configuration; + @Override + public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { + CorsConfiguration configuration = new CorsConfiguration(); + configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000")); + configuration.setAllowedMethods(Collections.singletonList("*")); + configuration.setAllowCredentials(true); + configuration.setAllowedHeaders(Collections.singletonList("*")); + configuration.setMaxAge(3600L); + configuration.setExposedHeaders(Collections.singletonList("Authorization")); + return configuration; } })); // CSRF 보호 비활성화 - http.csrf(csrf -> csrf.disable()); + http.csrf(AbstractHttpConfigurer::disable); // 폼 로그인 비활성화 - http.formLogin(login -> login.disable()); + http.formLogin(AbstractHttpConfigurer::disable); // HTTP Basic 인증 비활성화 - http.httpBasic(basic -> basic.disable()); + http.httpBasic(AbstractHttpConfigurer::disable); - //JWTFilter 추가 -// http.addFilterBefore(new JWTFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class); + // OAuth2 로그인 설정 + http.oauth2Login(oauth2 -> oauth2.userInfoEndpoint(userInfo -> userInfo.userService(customOAuth2UserService)) + .successHandler(customSuccessHandler)); - // 재로그인 방지를 위한 JWTFilter 선행해서 실행 + // JWT 필터 설정 +// http.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class); http.addFilterAfter(new JWTFilter(jwtUtil), OAuth2LoginAuthenticationFilter.class); + // 경로별 인가 작업 + http.authorizeHttpRequests(auth -> auth + .requestMatchers(WHITE_LIST_URL).permitAll() + .anyRequest().authenticated()); - //oauth2 - http.oauth2Login(oauth2 -> oauth2.userInfoEndpoint((userInfoEndpointConfig) -> userInfoEndpointConfig - .userService(customOAuth2UserService)) - .successHandler(customSuccessHandler) - ); + // 세션 설정: STATELESS + http.sessionManagement(session -> session.sessionCreationPolicy(STATELESS)); - //경로별 인가 작업 - http.authorizeHttpRequests((auth) -> auth - .requestMatchers("/").permitAll() - .anyRequest().authenticated()); // 나머지 주소는 인증 - - //세션 설정 : STATELESS - http.sessionManagement((session) -> session - .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); + // 로그아웃 설정 + http.logout(logout -> logout.logoutUrl("/api/v1/auth/logout").addLogoutHandler(logoutHandler)); return http.build(); } - - private static final String[] WHITE_LIST_URL = { "/api/v1/auth/**", @@ -127,26 +101,4 @@ public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { "/webjars/**", "/swagger-ui.html" }; - - @Bean - public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { - http - .csrf(AbstractHttpConfigurer::disable) - .authorizeHttpRequests(req -> - req.requestMatchers(WHITE_LIST_URL) - .permitAll() - .anyRequest() - .authenticated() - ) - .sessionManagement(session -> session.sessionCreationPolicy(STATELESS)) - .authenticationProvider(authenticationProvider) - .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) - .logout(logout -> - logout.logoutUrl("/api/v1/auth/logout") - .addLogoutHandler(logoutHandler) - ) - ; - - return http.build(); - } } diff --git a/src/main/java/com/kakaoteck/golagola/controller/MainController.java b/src/main/java/com/kakaoteck/golagola/controller/MainController.java deleted file mode 100644 index fa726ea..0000000 --- a/src/main/java/com/kakaoteck/golagola/controller/MainController.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.kakaoteck.golagola.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -@Controller -public class MainController { - - @GetMapping("/") - @ResponseBody - public String index(){ - return "main route"; - } -} - diff --git a/src/main/java/com/kakaoteck/golagola/controller/MyController.java b/src/main/java/com/kakaoteck/golagola/controller/MyController.java deleted file mode 100644 index 032f8ef..0000000 --- a/src/main/java/com/kakaoteck/golagola/controller/MyController.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.kakaoteck.golagola.controller; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -@Controller -public class MyController { - - @GetMapping("/my") - @ResponseBody - public String myApi(){ - return "myApi"; - } - -} diff --git a/src/main/java/com/kakaoteck/golagola/Repository/UserRepository.java b/src/main/java/com/kakaoteck/golagola/domain/auth/Repository/UserRepository.java similarity index 69% rename from src/main/java/com/kakaoteck/golagola/Repository/UserRepository.java rename to src/main/java/com/kakaoteck/golagola/domain/auth/Repository/UserRepository.java index f6983a1..73bebfb 100644 --- a/src/main/java/com/kakaoteck/golagola/Repository/UserRepository.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/Repository/UserRepository.java @@ -1,6 +1,6 @@ -package com.kakaoteck.golagola.Repository; +package com.kakaoteck.golagola.domain.auth.Repository; -import com.kakaoteck.golagola.entity.UserEntity; +import com.kakaoteck.golagola.domain.auth.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { diff --git a/src/main/java/com/kakaoteck/golagola/dto/CustomOAuth2User.java b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/CustomOAuth2User.java similarity index 95% rename from src/main/java/com/kakaoteck/golagola/dto/CustomOAuth2User.java rename to src/main/java/com/kakaoteck/golagola/domain/auth/dto/CustomOAuth2User.java index 90d7cdb..7490cab 100644 --- a/src/main/java/com/kakaoteck/golagola/dto/CustomOAuth2User.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/CustomOAuth2User.java @@ -1,4 +1,4 @@ -package com.kakaoteck.golagola.dto; +package com.kakaoteck.golagola.domain.auth.dto; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.user.OAuth2User; diff --git a/src/main/java/com/kakaoteck/golagola/dto/KakaoResponse.java b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/KakaoResponse.java similarity index 95% rename from src/main/java/com/kakaoteck/golagola/dto/KakaoResponse.java rename to src/main/java/com/kakaoteck/golagola/domain/auth/dto/KakaoResponse.java index 8ba8eb4..3448c19 100644 --- a/src/main/java/com/kakaoteck/golagola/dto/KakaoResponse.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/KakaoResponse.java @@ -1,4 +1,4 @@ -package com.kakaoteck.golagola.dto; +package com.kakaoteck.golagola.domain.auth.dto; import java.util.Map; diff --git a/src/main/java/com/kakaoteck/golagola/dto/NaverResponse.java b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/NaverResponse.java similarity index 90% rename from src/main/java/com/kakaoteck/golagola/dto/NaverResponse.java rename to src/main/java/com/kakaoteck/golagola/domain/auth/dto/NaverResponse.java index b6db7e5..9187b11 100644 --- a/src/main/java/com/kakaoteck/golagola/dto/NaverResponse.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/NaverResponse.java @@ -1,6 +1,5 @@ -package com.kakaoteck.golagola.dto; +package com.kakaoteck.golagola.domain.auth.dto; -import java.io.Serializable; import java.util.Map; public class NaverResponse implements OAuth2Response{ diff --git a/src/main/java/com/kakaoteck/golagola/dto/OAuth2Response.java b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/OAuth2Response.java similarity index 85% rename from src/main/java/com/kakaoteck/golagola/dto/OAuth2Response.java rename to src/main/java/com/kakaoteck/golagola/domain/auth/dto/OAuth2Response.java index c138a9f..423ed92 100644 --- a/src/main/java/com/kakaoteck/golagola/dto/OAuth2Response.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/OAuth2Response.java @@ -1,4 +1,4 @@ -package com.kakaoteck.golagola.dto; +package com.kakaoteck.golagola.domain.auth.dto; public interface OAuth2Response { diff --git a/src/main/java/com/kakaoteck/golagola/dto/UserDTO.java b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/UserDTO.java similarity index 77% rename from src/main/java/com/kakaoteck/golagola/dto/UserDTO.java rename to src/main/java/com/kakaoteck/golagola/domain/auth/dto/UserDTO.java index ff7b49f..c5b7ca5 100644 --- a/src/main/java/com/kakaoteck/golagola/dto/UserDTO.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/dto/UserDTO.java @@ -1,4 +1,4 @@ -package com.kakaoteck.golagola.dto; +package com.kakaoteck.golagola.domain.auth.dto; import lombok.Getter; import lombok.Setter; diff --git a/src/main/java/com/kakaoteck/golagola/entity/UserEntity.java b/src/main/java/com/kakaoteck/golagola/domain/auth/entity/UserEntity.java similarity index 89% rename from src/main/java/com/kakaoteck/golagola/entity/UserEntity.java rename to src/main/java/com/kakaoteck/golagola/domain/auth/entity/UserEntity.java index 3ec1254..cf39f40 100644 --- a/src/main/java/com/kakaoteck/golagola/entity/UserEntity.java +++ b/src/main/java/com/kakaoteck/golagola/domain/auth/entity/UserEntity.java @@ -1,4 +1,4 @@ -package com.kakaoteck.golagola.entity; +package com.kakaoteck.golagola.domain.auth.entity; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; diff --git a/src/main/java/com/kakaoteck/golagola/jwt/JWTFilter.java b/src/main/java/com/kakaoteck/golagola/security/jwt/JWTFilter.java similarity index 64% rename from src/main/java/com/kakaoteck/golagola/jwt/JWTFilter.java rename to src/main/java/com/kakaoteck/golagola/security/jwt/JWTFilter.java index 3c03194..5c2b340 100644 --- a/src/main/java/com/kakaoteck/golagola/jwt/JWTFilter.java +++ b/src/main/java/com/kakaoteck/golagola/security/jwt/JWTFilter.java @@ -1,7 +1,7 @@ -package com.kakaoteck.golagola.jwt; +package com.kakaoteck.golagola.security.jwt; -import com.kakaoteck.golagola.dto.CustomOAuth2User; -import com.kakaoteck.golagola.dto.UserDTO; +import com.kakaoteck.golagola.domain.auth.dto.CustomOAuth2User; +import com.kakaoteck.golagola.domain.auth.dto.UserDTO; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; @@ -25,60 +25,55 @@ public JWTFilter(JWTUtil jwtUtil) { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { - //cookie들을 불러온 뒤 Authorization Key에 담긴 쿠키를 찾음 + // 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(); + // 쿠키가 null인지 확인 + if (cookies != null) { + for (Cookie cookie : cookies) { + System.out.println(cookie.getName()); + if (cookie.getName().equals("Authorization")) { + authorization = cookie.getValue(); + } } } - //Authorization 헤더 검증 + // Authorization 헤더 검증 if (authorization == null) { - System.out.println("token null"); filterChain.doFilter(request, response); - - //조건이 해당되면 메소드 종료 (필수) - return; + return; // 조건이 해당되면 메소드 종료 (필수) } - //토큰 + // 토큰 String token = authorization; - //토큰 소멸 시간 검증 + // 토큰 소멸 시간 검증 if (jwtUtil.isExpired(token)) { - System.out.println("token expired"); filterChain.doFilter(request, response); - - //조건이 해당되면 메소드 종료 (필수) - return; + return; // 조건이 해당되면 메소드 종료 (필수) } - //토큰에서 username과 role 획득 + // 토큰에서 username과 role 획득 String username = jwtUtil.getUsername(token); String role = jwtUtil.getRole(token); - //userDTO를 생성하여 값 set + // userDTO를 생성하여 값 set UserDTO userDTO = new UserDTO(); userDTO.setUsername(username); userDTO.setRole(role); - //UserDetails에 회원 정보 객체 담기 + // UserDetails에 회원 정보 객체 담기 CustomOAuth2User customOAuth2User = new CustomOAuth2User(userDTO); - //스프링 시큐리티 인증 토큰 생성 + // 스프링 시큐리티 인증 토큰 생성 Authentication authToken = new UsernamePasswordAuthenticationToken(customOAuth2User, null, customOAuth2User.getAuthorities()); - //세션에 사용자 등록 + // 세션에 사용자 등록 SecurityContextHolder.getContext().setAuthentication(authToken); filterChain.doFilter(request, response); - } } diff --git a/src/main/java/com/kakaoteck/golagola/jwt/JWTUtil.java b/src/main/java/com/kakaoteck/golagola/security/jwt/JWTUtil.java similarity index 97% rename from src/main/java/com/kakaoteck/golagola/jwt/JWTUtil.java rename to src/main/java/com/kakaoteck/golagola/security/jwt/JWTUtil.java index 3d8b8c5..8ec742b 100644 --- a/src/main/java/com/kakaoteck/golagola/jwt/JWTUtil.java +++ b/src/main/java/com/kakaoteck/golagola/security/jwt/JWTUtil.java @@ -1,4 +1,4 @@ -package com.kakaoteck.golagola.jwt; +package com.kakaoteck.golagola.security.jwt; import io.jsonwebtoken.Jwts; import org.springframework.beans.factory.annotation.Value; @@ -44,4 +44,4 @@ public String createJwt(String username, String role, Long expiredMs) { .compact(); } -} +} \ No newline at end of file diff --git a/src/main/java/com/kakaoteck/golagola/oauth2/CustomSuccessHandler.java b/src/main/java/com/kakaoteck/golagola/security/oauth2/CustomSuccessHandler.java similarity index 89% rename from src/main/java/com/kakaoteck/golagola/oauth2/CustomSuccessHandler.java rename to src/main/java/com/kakaoteck/golagola/security/oauth2/CustomSuccessHandler.java index 5057e20..b8ae13f 100644 --- a/src/main/java/com/kakaoteck/golagola/oauth2/CustomSuccessHandler.java +++ b/src/main/java/com/kakaoteck/golagola/security/oauth2/CustomSuccessHandler.java @@ -1,7 +1,7 @@ -package com.kakaoteck.golagola.oauth2; +package com.kakaoteck.golagola.security.oauth2; -import com.kakaoteck.golagola.dto.CustomOAuth2User; -import com.kakaoteck.golagola.jwt.JWTUtil; +import com.kakaoteck.golagola.domain.auth.dto.CustomOAuth2User; +import com.kakaoteck.golagola.security.jwt.JWTUtil; import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; @@ -39,7 +39,7 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo String token = jwtUtil.createJwt(username, role, 60*60*60L); response.addCookie(createCookie("Authorization", token)); // 쿠키를 넣어준다. - response.sendRedirect("http://localhost:3000/"); // 프론트쪽으로 특정 uri로 리다이렉트 + response.sendRedirect("http://localhost:8080/"); // 프론트쪽으로 특정 uri로 리다이렉트 } private Cookie createCookie(String key, String value) { diff --git a/src/main/java/com/kakaoteck/golagola/security/service/JwtService.java b/src/main/java/com/kakaoteck/golagola/security/service/JwtService.java index 66a7da3..8c1c652 100644 --- a/src/main/java/com/kakaoteck/golagola/security/service/JwtService.java +++ b/src/main/java/com/kakaoteck/golagola/security/service/JwtService.java @@ -20,8 +20,10 @@ public class JwtService { @Value("${spring.jwt.secret}") private String secretKey; + @Value("${spring.jwt.token.access-expiration-time}") private long jwtExpiration; + @Value("${spring.jwt.token.refresh-expiration-time}") private long refreshExpiration; @@ -39,16 +41,7 @@ public String generateToken(UserDetails userDetails) { } public String generateToken(Map extraClaims, UserDetails userDetails) { - String token = null; - try { - token = buildToken(extraClaims, userDetails, jwtExpiration); - System.out.println("Generated JWT Token: " + token); - } catch (Exception e) { - e.printStackTrace(); - // 로그 추가 - System.out.println("JWT Token 생성 중 오류 발생: " + e.getMessage()); - } - return token; + return buildToken(extraClaims, userDetails, jwtExpiration); } public boolean isTokenValid(String token, UserDetails userDetails) { @@ -64,13 +57,8 @@ public String generateRefreshToken(UserDetails userDetails) { return buildToken(new HashMap<>(), userDetails, refreshExpiration); } - private String buildToken( - Map extraClaims, - UserDetails userDetails, - long expiration - ) { - return Jwts - .builder() + private String buildToken(Map extraClaims, UserDetails userDetails, long expiration) { + return Jwts.builder() .setClaims(extraClaims) .setSubject(userDetails.getUsername()) .setIssuedAt(new Date(System.currentTimeMillis())) @@ -84,17 +72,15 @@ private Date extractExpiration(String token) { } private Claims extractAllClaims(String token) { - return Jwts - .parserBuilder() + return Jwts.parser() // parserBuilder() 대신 parser() 사용 .setSigningKey(getSignInKey()) .build() - .parseClaimsJws(token) - .getBody(); + .parseSignedClaims(token) + .getPayload(); } private Key getSignInKey() { byte[] keyBytes = Decoders.BASE64.decode(secretKey); return Keys.hmacShaKeyFor(keyBytes); } - } diff --git a/src/main/java/com/kakaoteck/golagola/service/CustomOAuth2UserService.java b/src/main/java/com/kakaoteck/golagola/service/CustomOAuth2UserService.java index 9236525..7bd9ec4 100644 --- a/src/main/java/com/kakaoteck/golagola/service/CustomOAuth2UserService.java +++ b/src/main/java/com/kakaoteck/golagola/service/CustomOAuth2UserService.java @@ -1,8 +1,8 @@ package com.kakaoteck.golagola.service; -import com.kakaoteck.golagola.Repository.UserRepository; -import com.kakaoteck.golagola.dto.*; -import com.kakaoteck.golagola.entity.UserEntity; +import com.kakaoteck.golagola.domain.auth.Repository.UserRepository; +import com.kakaoteck.golagola.domain.auth.dto.*; +import com.kakaoteck.golagola.domain.auth.entity.UserEntity; import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 9a51c12..bec2749 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -4,13 +4,17 @@ spring.application.name=golagola spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/golagola?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource.username=root -spring.datasource.password=00000000 +spring.datasource.password=8253 spring.jpa.hibernate.ddl-auto=create spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl # JWT spring.jwt.secret=vmfhaltmskdlstkfkdgodyroqkfwkdbalroqkfwkdballywaaaaaaaaaaaaabbbbb +spring.jwt.token.access-expiration-time=86400000 +spring.jwt.token.refresh-expiration-time=86400000 +spring.data.redis.host=localhost +spring.data.redis.port=6379 # 1) Kakao #registration