From 04b1b3b194943fe389e11b63f01f65aa85685590 Mon Sep 17 00:00:00 2001 From: toychip Date: Tue, 13 Feb 2024 04:07:41 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20kakao=20accessToken=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=EB=A1=9C=EA=B7=B8=EC=9D=B8,=20Server=20jwt=20=EB=B0=9C?= =?UTF-8?q?=EA=B8=89=20(#51)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../domain/common/base/BaseEntityConfig.java | 20 ++- .../domain/member/service/MemberService.java | 10 +- .../ttoklip/global/config/SecurityConfig.java | 42 ++--- .../ttoklip/global/exception/ErrorType.java | 1 + .../global/security/auth/UserPrincipal.java | 66 -------- .../auth/controller/AuthController.java | 9 +- .../security/auth/dto/LoginResponse.java | 9 +- .../auth/handler/AuthFailureHandler.java | 36 +++++ .../auth/handler/TokenErrorHandler.java | 17 +++ .../security/auth/service/AuthService.java | 39 ++++- .../auth/service/OAuth2UserInfoFactory.java | 6 +- .../auth/service/UserDetailsServiceImpl.java | 26 ---- .../userInfo/KakaoUserInfo.java | 10 +- .../userInfo/NaverUserInfo.java | 2 +- .../userInfo/OAuth2UserInfo.java | 2 +- .../security/jwt/JwtAuthenticationFilter.java | 7 +- .../global/security/jwt/JwtProvider.java | 8 +- .../security/oauth/response/AuthResponse.java | 7 - .../service/CustomOAuth2UserService.java | 143 ------------------ 19 files changed, 141 insertions(+), 319 deletions(-) delete mode 100644 src/main/java/com/api/ttoklip/global/security/auth/UserPrincipal.java create mode 100644 src/main/java/com/api/ttoklip/global/security/auth/handler/AuthFailureHandler.java create mode 100644 src/main/java/com/api/ttoklip/global/security/auth/handler/TokenErrorHandler.java delete mode 100644 src/main/java/com/api/ttoklip/global/security/auth/service/UserDetailsServiceImpl.java rename src/main/java/com/api/ttoklip/global/security/{oauth => auth}/userInfo/KakaoUserInfo.java (71%) rename src/main/java/com/api/ttoklip/global/security/{oauth => auth}/userInfo/NaverUserInfo.java (91%) rename src/main/java/com/api/ttoklip/global/security/{oauth => auth}/userInfo/OAuth2UserInfo.java (65%) delete mode 100644 src/main/java/com/api/ttoklip/global/security/oauth/response/AuthResponse.java delete mode 100644 src/main/java/com/api/ttoklip/global/security/oauth/service/CustomOAuth2UserService.java diff --git a/src/main/java/com/api/ttoklip/domain/common/base/BaseEntityConfig.java b/src/main/java/com/api/ttoklip/domain/common/base/BaseEntityConfig.java index 955e7442..14b75ba6 100644 --- a/src/main/java/com/api/ttoklip/domain/common/base/BaseEntityConfig.java +++ b/src/main/java/com/api/ttoklip/domain/common/base/BaseEntityConfig.java @@ -18,12 +18,24 @@ public AuditorAware auditorProvider() { return () -> { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { - return Optional.of("Anonymous"); + return Optional.of("AnonymousNULL"); + } + + System.out.println("authentication = " + authentication); + System.out.println("----------- 클래스 타입" + authentication.getClass()); + System.out.println("----------- 클래스 타입" + authentication.getPrincipal().getClass()); + + + Object principal = authentication.getPrincipal(); + if (principal instanceof Member) { + Member member = (Member) principal; + String email = member.getEmail(); + return Optional.ofNullable(email); + } else { + // principal이 Member 타입이 아닌 경우의 처리 + return Optional.of("AnonymousNOT_TYPE"); } - Member member = (Member) authentication.getPrincipal(); - String originName = member.getOriginName(); - return Optional.of(originName); }; } } diff --git a/src/main/java/com/api/ttoklip/domain/member/service/MemberService.java b/src/main/java/com/api/ttoklip/domain/member/service/MemberService.java index 850d853d..660c7688 100644 --- a/src/main/java/com/api/ttoklip/domain/member/service/MemberService.java +++ b/src/main/java/com/api/ttoklip/domain/member/service/MemberService.java @@ -19,11 +19,6 @@ public class MemberService { private final MemberRepository memberRepository; private final MemberOAuthRepository memberOAuthRepository; - public Member findByIdOfToken(final Long memberId) { - return memberRepository.findById(memberId) - .orElseThrow(() -> new ApiException(_USER_NOT_FOUND_BY_TOKEN)); - } - public Member findByIdWithProfile(final Long memberId) { return memberOAuthRepository.findByIdWithProfile(memberId); } @@ -41,4 +36,9 @@ public Optional findByEmailOptional(final String email) { return memberRepository.findByEmail(email); } + + @Transactional + public void register(final Member member) { + memberRepository.save(member); + } } diff --git a/src/main/java/com/api/ttoklip/global/config/SecurityConfig.java b/src/main/java/com/api/ttoklip/global/config/SecurityConfig.java index b0cf36ad..47f3500d 100644 --- a/src/main/java/com/api/ttoklip/global/config/SecurityConfig.java +++ b/src/main/java/com/api/ttoklip/global/config/SecurityConfig.java @@ -1,8 +1,7 @@ package com.api.ttoklip.global.config; +import com.api.ttoklip.global.security.auth.handler.TokenErrorHandler; import com.api.ttoklip.global.security.jwt.JwtAuthenticationFilter; -import com.api.ttoklip.global.security.oauth.service.CustomOAuth2UserService; -import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -22,56 +21,34 @@ @RequiredArgsConstructor public class SecurityConfig { - private final CustomOAuth2UserService customOAuth2UserService; private final JwtAuthenticationFilter jwtAuthenticationFilter; - private final CustomOAuthSuccessHandler customOAuthSuccessHandler; + private final TokenErrorHandler tokenErrorHandler; @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .httpBasic(HttpBasicConfigurer::disable) .csrf(CsrfConfigurer::disable) - .cors(corsCustomizer -> corsCustomizer.configurationSource(request -> { - CorsConfiguration cors = new CorsConfiguration(); - cors.setAllowedOrigins(List.of("*", "http://localhost:3000", "http://localhost:8080")); - cors.setAllowedMethods(List.of("GET", "POST", "PATCH", "DELETE")); - // cookie 비활성화 - cors.setAllowCredentials(false); - // Authorization Header 노출 - cors.addExposedHeader("Authorization"); - return cors; - })) + .cors() + .and() .sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(authorize -> authorize .requestMatchers( "/favicon.ico" - ,"/health" - ,"/swagger-ui/**" - ,"/oauth/**" - ,"/login/**" + , "/health" + , "/swagger-ui/**" + , "/oauth/**" + , "/login/**" , "/**" ).permitAll() .anyRequest().permitAll()); - - // ToDo oauth 설정, filter, Handler 등 - - http .oauth2Login() - .authorizationEndpoint().baseUri("/oauth/authorize") - .and() - .redirectionEndpoint().baseUri("/oauth/callback") - .and() - .userInfoEndpoint() // oauth2 로그인 성공후에 사용자 정보를 바로 가져온다. - .userService(customOAuth2UserService) - .and() - .successHandler(customOAuthSuccessHandler); - + http.exceptionHandling(e -> e.accessDeniedHandler(tokenErrorHandler)); http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); } - // CORS @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); @@ -84,5 +61,4 @@ public CorsFilter corsFilter() { source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } - } diff --git a/src/main/java/com/api/ttoklip/global/exception/ErrorType.java b/src/main/java/com/api/ttoklip/global/exception/ErrorType.java index cc6035c7..f365c7b4 100644 --- a/src/main/java/com/api/ttoklip/global/exception/ErrorType.java +++ b/src/main/java/com/api/ttoklip/global/exception/ErrorType.java @@ -73,6 +73,7 @@ public enum ErrorType { // ------------------------------------------ Auth ------------------------------------------ OAUTH_INVALID_PROVIDER(INTERNAL_SERVER_ERROR, "OAUTH_5000", "올바르지 않은 Provider입니다."), OAUTH_NOTFOUND_NAME(INTERNAL_SERVER_ERROR, "OAUTH_5001", "Oauth 제공자로부터 name을 받을 수 없습니다."), + OAUTH_NOTFOUND_EMAIL(INTERNAL_SERVER_ERROR, "OAUTH_5002", "Oauth 제공자로부터 email을 받을 수 없습니다."), // ------------------------------------------ USER ------------------------------------------ diff --git a/src/main/java/com/api/ttoklip/global/security/auth/UserPrincipal.java b/src/main/java/com/api/ttoklip/global/security/auth/UserPrincipal.java deleted file mode 100644 index effc647e..00000000 --- a/src/main/java/com/api/ttoklip/global/security/auth/UserPrincipal.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.api.ttoklip.global.security.auth; - -import com.api.ttoklip.domain.member.domain.Member; -import com.api.ttoklip.domain.member.domain.Role; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import lombok.Getter; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UserDetails; - -@Getter -public class UserPrincipal implements UserDetails { - - private transient final Member member; - - private transient Map attributes; - - public UserPrincipal(final Member member) { - this.member = member; - } - - public static UserPrincipal create(Member member) { - return new UserPrincipal(member); - } - - @Override - public Collection getAuthorities() { - return Collections.singletonList(new SimpleGrantedAuthority(getRoleFromMemberType())); - } - - public String getRoleFromMemberType() { - return ""; - } - - @Override - public String getPassword() { - return null; - } - - @Override - public String getUsername() { - return member.getEmail(); - } - - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean isEnabled() { - return true; - } -} diff --git a/src/main/java/com/api/ttoklip/global/security/auth/controller/AuthController.java b/src/main/java/com/api/ttoklip/global/security/auth/controller/AuthController.java index 87cc11af..cfd235fc 100644 --- a/src/main/java/com/api/ttoklip/global/security/auth/controller/AuthController.java +++ b/src/main/java/com/api/ttoklip/global/security/auth/controller/AuthController.java @@ -2,9 +2,9 @@ import com.api.ttoklip.global.security.auth.dto.LoginRequest; import com.api.ttoklip.global.security.auth.dto.LoginResponse; +import com.api.ttoklip.global.security.auth.service.AuthService; import com.api.ttoklip.global.success.SuccessResponse; import lombok.RequiredArgsConstructor; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -14,10 +14,11 @@ @RequiredArgsConstructor @RequestMapping("/api/v1/auth") public class AuthController { + private final AuthService authService; @PostMapping - public SuccessResponse loginWithKakao(@RequestBody LoginRequest request) { - - return null; + public SuccessResponse login(final @RequestBody LoginRequest request) { + LoginResponse loginResponse = authService.authenticate(request); + return new SuccessResponse<>(loginResponse); } } diff --git a/src/main/java/com/api/ttoklip/global/security/auth/dto/LoginResponse.java b/src/main/java/com/api/ttoklip/global/security/auth/dto/LoginResponse.java index da42db10..b350cc78 100644 --- a/src/main/java/com/api/ttoklip/global/security/auth/dto/LoginResponse.java +++ b/src/main/java/com/api/ttoklip/global/security/auth/dto/LoginResponse.java @@ -1,14 +1,7 @@ package com.api.ttoklip.global.security.auth.dto; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; import lombok.Builder; -import lombok.Getter; -@Getter @Builder -@AllArgsConstructor(access = AccessLevel.PRIVATE) -public class LoginResponse { - private String jwtToken; - private boolean ifFirstLogin; +public record LoginResponse(String jwtToken, boolean ifFirstLogin) { } diff --git a/src/main/java/com/api/ttoklip/global/security/auth/handler/AuthFailureHandler.java b/src/main/java/com/api/ttoklip/global/security/auth/handler/AuthFailureHandler.java new file mode 100644 index 00000000..45aba675 --- /dev/null +++ b/src/main/java/com/api/ttoklip/global/security/auth/handler/AuthFailureHandler.java @@ -0,0 +1,36 @@ +package com.api.ttoklip.global.security.auth.handler; + +import com.api.ttoklip.global.exception.ApiException; +import com.api.ttoklip.global.exception.ErrorType; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.AuthenticationFailureHandler; +import org.springframework.stereotype.Component; + +@Component +public class AuthFailureHandler implements AuthenticationFailureHandler { + + @Override + public void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response, + final AuthenticationException authException) throws IOException { + ApiException apiException = (ApiException) authException.getCause(); + ErrorType errorType = apiException.getErrorType(); + setResponse(response, errorType); + } + + private void setResponse(HttpServletResponse response, ErrorType errorType) throws IOException { + + response.setContentType("application/json;charset=UTF-8"); + + int status = Integer.parseInt(String.valueOf(errorType.getStatus()).substring(0,3)); + response.setStatus(status); + + response.getWriter().println( + "{\"status\" : \"" + status + "\"," + + "\"errorCode\" : \"" + errorType.getErrorCode() + "\"," + + " \"message\" : \"" + errorType.getMessage() + + "\"}"); + } +} \ No newline at end of file diff --git a/src/main/java/com/api/ttoklip/global/security/auth/handler/TokenErrorHandler.java b/src/main/java/com/api/ttoklip/global/security/auth/handler/TokenErrorHandler.java new file mode 100644 index 00000000..e5b181b8 --- /dev/null +++ b/src/main/java/com/api/ttoklip/global/security/auth/handler/TokenErrorHandler.java @@ -0,0 +1,17 @@ +package com.api.ttoklip.global.security.auth.handler; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.access.AccessDeniedHandler; +import org.springframework.stereotype.Component; + +@Component +public class TokenErrorHandler implements AccessDeniedHandler { + // 권한 부족시 호출되는 핸들러 + @Override + public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException { + response.sendError(HttpServletResponse.SC_FORBIDDEN); + } +} diff --git a/src/main/java/com/api/ttoklip/global/security/auth/service/AuthService.java b/src/main/java/com/api/ttoklip/global/security/auth/service/AuthService.java index 1132d69e..9bfbfe4c 100644 --- a/src/main/java/com/api/ttoklip/global/security/auth/service/AuthService.java +++ b/src/main/java/com/api/ttoklip/global/security/auth/service/AuthService.java @@ -1,11 +1,15 @@ package com.api.ttoklip.global.security.auth.service; import com.api.ttoklip.domain.member.domain.Member; +import com.api.ttoklip.domain.member.domain.Role; import com.api.ttoklip.domain.member.service.MemberService; +import com.api.ttoklip.domain.privacy.domain.Profile; +import com.api.ttoklip.domain.privacy.service.ProfileService; import com.api.ttoklip.global.security.auth.dto.LoginRequest; import com.api.ttoklip.global.security.auth.dto.LoginResponse; import com.api.ttoklip.global.security.jwt.JwtProvider; -import com.api.ttoklip.global.security.oauth.userInfo.OAuth2UserInfo; +import com.api.ttoklip.global.security.auth.userInfo.OAuth2UserInfo; +import java.util.Optional; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @@ -16,6 +20,7 @@ public class AuthService { private final MemberService memberService; private final OAuth2UserInfoFactory oAuth2UserInfoFactory; private final JwtProvider jwtProvider; + private final ProfileService profileService; public LoginResponse authenticate(final LoginRequest request) { String provider = request.getProvider(); @@ -24,15 +29,39 @@ public LoginResponse authenticate(final LoginRequest request) { OAuth2UserInfo userInfo = oAuth2UserInfoFactory.getUserInfo(provider, accessToken); String email = userInfo.getEmail(); - Member member = memberService.findByEmailOptional(email) -// .orElseGet() // 회원가입 or 로그인 처리 + Optional memberOptional = memberService.findByEmailOptional(email); + if (memberOptional.isPresent()) { + Member member = memberOptional.get(); + return getLoginResponse(member, false); + } + Member member = registerNewMember(userInfo, provider); + return getLoginResponse(member, true); + } + + private LoginResponse getLoginResponse(final Member member, final boolean ifFirstLogin) { // Server JWT Token String jwtToken = jwtProvider.generateJwtToken(member.getEmail()); - return LoginResponse.builder() .jwtToken(jwtToken) -// .ifFirstLogin() + .ifFirstLogin(ifFirstLogin) + .build(); + } + + private Member registerNewMember(final OAuth2UserInfo userInfo, final String provider) { + System.out.println("AuthService.registerNewMember"); + System.out.println("userInfo.getName() = " + userInfo.getName()); + Member newMember = Member.builder() + .email(userInfo.getEmail()) + .originName(userInfo.getName()) + .provider(provider) + .role(Role.CLIENT) .build(); + memberService.register(newMember); + + Profile profile = Profile.of(newMember, userInfo.getProfile()); + profileService.register(profile); + + return newMember; } } diff --git a/src/main/java/com/api/ttoklip/global/security/auth/service/OAuth2UserInfoFactory.java b/src/main/java/com/api/ttoklip/global/security/auth/service/OAuth2UserInfoFactory.java index 9cfdd538..d409c7d4 100644 --- a/src/main/java/com/api/ttoklip/global/security/auth/service/OAuth2UserInfoFactory.java +++ b/src/main/java/com/api/ttoklip/global/security/auth/service/OAuth2UserInfoFactory.java @@ -2,8 +2,8 @@ import com.api.ttoklip.global.exception.ApiException; import com.api.ttoklip.global.exception.ErrorType; -import com.api.ttoklip.global.security.oauth.userInfo.KakaoUserInfo; -import com.api.ttoklip.global.security.oauth.userInfo.OAuth2UserInfo; +import com.api.ttoklip.global.security.auth.userInfo.KakaoUserInfo; +import com.api.ttoklip.global.security.auth.userInfo.OAuth2UserInfo; import java.util.Map; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -46,7 +46,7 @@ private KakaoUserInfo getKakaoUserInfo(String token) { .bodyToMono(new ParameterizedTypeReference>() { }) .block(); - + System.out.println("---------------------------------------- attributes = " + attributes); return new KakaoUserInfo(attributes); } } diff --git a/src/main/java/com/api/ttoklip/global/security/auth/service/UserDetailsServiceImpl.java b/src/main/java/com/api/ttoklip/global/security/auth/service/UserDetailsServiceImpl.java deleted file mode 100644 index 5ba7fdfe..00000000 --- a/src/main/java/com/api/ttoklip/global/security/auth/service/UserDetailsServiceImpl.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.api.ttoklip.global.security.auth.service; - -import com.api.ttoklip.domain.member.domain.Member; -import com.api.ttoklip.domain.member.repository.MemberRepository; -import com.api.ttoklip.global.security.auth.UserPrincipal; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -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; - -@Slf4j -@Service -@RequiredArgsConstructor -public class UserDetailsServiceImpl implements UserDetailsService { - private final MemberRepository memberRepository; - - @Override - public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { - Member member = memberRepository.findByEmail(email) - .orElseThrow(() -> new UsernameNotFoundException("User not found with email: " + email)); - - return UserPrincipal.create(member); - } -} diff --git a/src/main/java/com/api/ttoklip/global/security/oauth/userInfo/KakaoUserInfo.java b/src/main/java/com/api/ttoklip/global/security/auth/userInfo/KakaoUserInfo.java similarity index 71% rename from src/main/java/com/api/ttoklip/global/security/oauth/userInfo/KakaoUserInfo.java rename to src/main/java/com/api/ttoklip/global/security/auth/userInfo/KakaoUserInfo.java index 77100f30..95d7b98a 100644 --- a/src/main/java/com/api/ttoklip/global/security/oauth/userInfo/KakaoUserInfo.java +++ b/src/main/java/com/api/ttoklip/global/security/auth/userInfo/KakaoUserInfo.java @@ -1,5 +1,7 @@ -package com.api.ttoklip.global.security.oauth.userInfo; +package com.api.ttoklip.global.security.auth.userInfo; +import com.api.ttoklip.global.exception.ApiException; +import com.api.ttoklip.global.exception.ErrorType; import java.util.Map; import lombok.AllArgsConstructor; import lombok.Getter; @@ -28,7 +30,11 @@ public String getName() { Map kakaoAccount = (Map) attributes.get("kakao_account"); Map kakaoProfile = (Map) kakaoAccount.get("profile"); - return (String) kakaoProfile.get("nickname"); + try { + return (String) kakaoProfile.get("nickname"); + } catch (NullPointerException e) { + throw new ApiException(ErrorType.OAUTH_NOTFOUND_EMAIL); + } } } diff --git a/src/main/java/com/api/ttoklip/global/security/oauth/userInfo/NaverUserInfo.java b/src/main/java/com/api/ttoklip/global/security/auth/userInfo/NaverUserInfo.java similarity index 91% rename from src/main/java/com/api/ttoklip/global/security/oauth/userInfo/NaverUserInfo.java rename to src/main/java/com/api/ttoklip/global/security/auth/userInfo/NaverUserInfo.java index 7f57c349..1830746e 100644 --- a/src/main/java/com/api/ttoklip/global/security/oauth/userInfo/NaverUserInfo.java +++ b/src/main/java/com/api/ttoklip/global/security/auth/userInfo/NaverUserInfo.java @@ -1,4 +1,4 @@ -package com.api.ttoklip.global.security.oauth.userInfo; +package com.api.ttoklip.global.security.auth.userInfo; import java.util.Map; import lombok.AllArgsConstructor; diff --git a/src/main/java/com/api/ttoklip/global/security/oauth/userInfo/OAuth2UserInfo.java b/src/main/java/com/api/ttoklip/global/security/auth/userInfo/OAuth2UserInfo.java similarity index 65% rename from src/main/java/com/api/ttoklip/global/security/oauth/userInfo/OAuth2UserInfo.java rename to src/main/java/com/api/ttoklip/global/security/auth/userInfo/OAuth2UserInfo.java index b27bcca0..3dd8e58a 100644 --- a/src/main/java/com/api/ttoklip/global/security/oauth/userInfo/OAuth2UserInfo.java +++ b/src/main/java/com/api/ttoklip/global/security/auth/userInfo/OAuth2UserInfo.java @@ -1,4 +1,4 @@ -package com.api.ttoklip.global.security.oauth.userInfo; +package com.api.ttoklip.global.security.auth.userInfo; public interface OAuth2UserInfo { String getProfile(); diff --git a/src/main/java/com/api/ttoklip/global/security/jwt/JwtAuthenticationFilter.java b/src/main/java/com/api/ttoklip/global/security/jwt/JwtAuthenticationFilter.java index ddadcfdb..7bba0c17 100644 --- a/src/main/java/com/api/ttoklip/global/security/jwt/JwtAuthenticationFilter.java +++ b/src/main/java/com/api/ttoklip/global/security/jwt/JwtAuthenticationFilter.java @@ -32,10 +32,7 @@ protected void doFilterInternal(final HttpServletRequest request, final HttpServ return; } - log.info("----- JWT filter do FilterInternal !!!!"); String authorizationHeader = request.getHeader("Authorization"); - log.info("------- authorizationHeader = " + authorizationHeader); - if (authorizationHeader != null && isBearer(authorizationHeader)) { try { // "Bearer " 이후의 문자열을 추출 @@ -66,8 +63,6 @@ private boolean isPublicUri(final String requestURI) { requestURI.startsWith("/swagger-ui/**") || requestURI.startsWith("/api/health") || requestURI.startsWith("/favicon.ico") || - requestURI.startsWith("/api/v1/search/**") || - requestURI.startsWith("/api/compile/**") || - requestURI.startsWith("/login/**"); + requestURI.startsWith("/api/v1/auth/**"); } } diff --git a/src/main/java/com/api/ttoklip/global/security/jwt/JwtProvider.java b/src/main/java/com/api/ttoklip/global/security/jwt/JwtProvider.java index c38884bf..ba1b124c 100644 --- a/src/main/java/com/api/ttoklip/global/security/jwt/JwtProvider.java +++ b/src/main/java/com/api/ttoklip/global/security/jwt/JwtProvider.java @@ -37,7 +37,6 @@ public class JwtProvider { private final MemberService memberService; @Value("${jwt.secret.key}") private String SECRET_KEY; - private final UserDetailsService userDetailsService; public String generateJwtToken(final String email) { @@ -92,26 +91,25 @@ public void isValidToken(final String jwtToken) { // jwtToken 으로 Authentication 에 사용자 등록 public void getAuthenticationFromToken(final String jwtToken) { Member loginMember = getMemberByToken(jwtToken); - UserDetails userDetails = userDetailsService.loadUserByUsername(loginMember.getEmail()); - // setContextHolder 메서드 내에서 로그 추가 setContextHolder(jwtToken, loginMember); } // token 으로부터 유저 정보 확인 private Member getMemberByToken(final String jwtToken) { String userEmail = getUserEmailFromToken(jwtToken); - return memberService.findByEmail(userEmail); } private void setContextHolder(String jwtToken, Member loginMember) { - // ToDO 현재 비어있는 권한 등록, 추후에 수정 List authorities = getAuthorities(loginMember.getRole()); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginMember, jwtToken, authorities); + System.out.println("------------------JwtProvider.setContextHolder"); SecurityContextHolder.getContext().setAuthentication(authenticationToken); + System.out.println("loginMember = " + loginMember.getEmail()); + System.out.println("------end------------JwtProvider.setContextHolder"); } private List getAuthorities(Role role) { diff --git a/src/main/java/com/api/ttoklip/global/security/oauth/response/AuthResponse.java b/src/main/java/com/api/ttoklip/global/security/oauth/response/AuthResponse.java deleted file mode 100644 index 7bd1802a..00000000 --- a/src/main/java/com/api/ttoklip/global/security/oauth/response/AuthResponse.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.api.ttoklip.global.security.oauth.response; - -import lombok.Builder; - -@Builder -public record AuthResponse(String token, Long memberId, String name, String profileImageUrl, boolean isFirstLogin) { -} diff --git a/src/main/java/com/api/ttoklip/global/security/oauth/service/CustomOAuth2UserService.java b/src/main/java/com/api/ttoklip/global/security/oauth/service/CustomOAuth2UserService.java deleted file mode 100644 index 4d5e9d1f..00000000 --- a/src/main/java/com/api/ttoklip/global/security/oauth/service/CustomOAuth2UserService.java +++ /dev/null @@ -1,143 +0,0 @@ -//package com.api.ttoklip.global.security.oauth.service; -// -//import com.api.ttoklip.domain.member.domain.Member; -//import com.api.ttoklip.domain.member.domain.Role; -//import com.api.ttoklip.domain.member.repository.MemberRepository; -//import com.api.ttoklip.domain.privacy.domain.Profile; -//import com.api.ttoklip.domain.privacy.service.ProfileService; -//import com.api.ttoklip.global.exception.ApiException; -//import com.api.ttoklip.global.exception.ErrorType; -//import com.api.ttoklip.global.security.oauth.principal.CustomOAuth2User; -//import com.api.ttoklip.global.security.oauth.userInfo.KakaoUserInfo; -//import com.api.ttoklip.global.security.oauth.userInfo.NaverUserInfo; -//import com.api.ttoklip.global.security.oauth.userInfo.OAuth2UserInfo; -//import com.api.ttoklip.global.security.oauth.userInfo.OAuthUserInfoFactory; -//import java.util.Map; -//import java.util.Optional; -//import lombok.RequiredArgsConstructor; -//import lombok.extern.slf4j.Slf4j; -//import org.springframework.security.core.userdetails.UserDetailsService; -//import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; -//import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; -//import org.springframework.security.oauth2.core.OAuth2AuthenticationException; -//import org.springframework.security.oauth2.core.user.OAuth2User; -//import org.springframework.stereotype.Service; -// -//@Slf4j -//@Service -//@RequiredArgsConstructor -//public class CustomOAuth2UserService extends DefaultOAuth2UserService { -// -// private final MemberRepository memberRepository; -// private final ProfileService profileService; -// private final UserDetailsService userDetailsService; -// -// @Override -// public OAuth2User loadUser(final OAuth2UserRequest request) throws OAuth2AuthenticationException { -// OAuth2User oAuth2User = super.loadUser(request); -// -// Map attributes = oAuth2User.getAttributes(); -// log.info("------------------ getAttributes : {}", attributes); -// -// String provider = request.getClientRegistration().getRegistrationId(); // 예: kakao, naver -// -// OAuth2UserInfo oAuth2UserInfo = OAuthUserInfoFactory.getOAuthAttributes(provider, attributes); -// -// /* -// // ToDo 관리자 기준 설정 -// String name = oAuth2UserInfo.getName(); -// if (email.equals("관리자")) { -// Role manager = Role.MANAGER; -// } -// */ -// -// if (provider.equals("naver")) { -// return handleMemberByNaver(provider, oAuth2UserInfo); -// } -// -// if (provider.equals("kakao")) { -// return handleMemberByKakao(provider, oAuth2UserInfo); -// } -// -// throw new ApiException(ErrorType.OAUTH_INVALID_PROVIDER); -// } -// -// // -------------------------------------------- DB 조회 및 회원 가입 -------------------------------------------- -// private CustomOAuth2User handleMemberByNaver(final String provider, final OAuth2UserInfo oAuth2UserInfo) { -// String email = ((NaverUserInfo) oAuth2UserInfo).getEmail(); -// Map attributes = ((NaverUserInfo) oAuth2UserInfo).getAttributes(); -// -// Optional memberOptional = memberRepository.findByNaverEmail(email); -// -// // 회원 정보가 있으면 로그인, 없으면 회원가입 -// if (memberOptional.isPresent()) { -// Member existingMember = memberOptional.get(); -// return CustomOAuth2User.login(existingMember, attributes); -// } -// -// Member newMember = registerMemberByNaver(oAuth2UserInfo, provider, email); -// return CustomOAuth2User.register(newMember, attributes); -// } -// -// private CustomOAuth2User handleMemberByKakao(final String provider, final OAuth2UserInfo oAuth2UserInfo) { -// Long kakaoId = ((KakaoUserInfo) oAuth2UserInfo).getKakaoId(); -// Map attributes = ((KakaoUserInfo) oAuth2UserInfo).getAttributes(); -// -// Optional memberOptional = memberRepository.findByKakaoId(kakaoId); -// -// // 회원 정보가 있으면 로그인, 없으면 회원가입 -// if (memberOptional.isPresent()) { -// Member existingMember = memberOptional.get(); -// return CustomOAuth2User.login(existingMember, attributes); -// } -// -// Member newMember = registerMemberByKakao(oAuth2UserInfo, provider, kakaoId); -// return CustomOAuth2User.register(newMember, attributes); -// } -// // -------------------------------------------- DB 조회 및 회원 가입 끝 -------------------------------------------- -// -// -// // -------------------------------------------- 회원가입 -------------------------------------------- -// private Member registerMemberByNaver(final OAuth2UserInfo oAuth2UserInfo, final String provider, -// final String email) { -// String name = oAuth2UserInfo.getName(); -// Member newMember = Member.builder() -// .originName(name) -// .naverEmail(email) -// .provider(provider) -// .role(Role.CLIENT) -// .build(); -// memberRepository.save(newMember); // 회원 저장 -// -// registerProfile(oAuth2UserInfo, newMember); -// -// return newMember; -// } -// -// private Member registerMemberByKakao(final OAuth2UserInfo oAuth2UserInfo, final String provider, -// final Long kakaoId) { -// String name = oAuth2UserInfo.getName(); -// Member newMember = Member.builder() -// .originName(name) -// .kakaoId(kakaoId) -// .provider(provider) -// .role(Role.CLIENT) -// .build(); -// memberRepository.save(newMember); // 회원 저장 -// -// registerProfile(oAuth2UserInfo, newMember); -// -// return newMember; -// } -// // -------------------------------------------- 회원가입 끝 -------------------------------------------- -// -// -// // -------------------------------------------- 프로필 생성 -------------------------------------------- -// private void registerProfile(final OAuth2UserInfo oAuth2UserInfo, final Member newMember) { -// // 프로필 생성 및 저장 -// String profileImageUrl = oAuth2UserInfo.getProfile(); -// Profile newProfile = Profile.of(newMember, profileImageUrl); -// profileService.register(newProfile); -// } -// // -------------------------------------------- 프로필 생성 -------------------------------------------- -//}