From 13751fe8940873767af7a8aef3ac51a8b65fc003 Mon Sep 17 00:00:00 2001 From: arinming Date: Tue, 16 Jan 2024 17:26:51 +0900 Subject: [PATCH 01/12] =?UTF-8?q?[FEAT]=20User=20->=20Member=EB=A1=9C=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20=EC=88=98=EC=A0=95=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../CustomDefaultOAuth2UserService.java | 14 ++++++------- ...e.java => CustomMemberDetailsService.java} | 10 +++++----- .../CustomTokenProviderService.java | 20 +++++++++---------- .../auth/controller/OauthController.java | 9 +++++++++ .../member/application/MemberService.java | 6 +++--- .../member/presentation/MemberController.java | 8 ++++---- .../config/security/SecurityConfig.java | 6 +++--- .../{CurrentUser.java => CurrentMember.java} | 2 +- ...serPrincipal.java => MemberPrincipal.java} | 16 +++++++-------- 9 files changed, 50 insertions(+), 41 deletions(-) rename src/main/java/com/ttubeog/domain/auth/application/{CustomUserDetailsService.java => CustomMemberDetailsService.java} (79%) create mode 100644 src/main/java/com/ttubeog/domain/auth/controller/OauthController.java rename src/main/java/com/ttubeog/global/config/security/token/{CurrentUser.java => CurrentMember.java} (89%) rename src/main/java/com/ttubeog/global/config/security/token/{UserPrincipal.java => MemberPrincipal.java} (80%) diff --git a/src/main/java/com/ttubeog/domain/auth/application/CustomDefaultOAuth2UserService.java b/src/main/java/com/ttubeog/domain/auth/application/CustomDefaultOAuth2UserService.java index 318adc6c..5e7d7577 100644 --- a/src/main/java/com/ttubeog/domain/auth/application/CustomDefaultOAuth2UserService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/CustomDefaultOAuth2UserService.java @@ -7,7 +7,7 @@ import com.ttubeog.global.DefaultAssert; import com.ttubeog.global.config.security.auth.OAuth2UserInfo; import com.ttubeog.global.config.security.auth.OAuth2UserInfoFactory; -import com.ttubeog.global.config.security.token.UserPrincipal; +import com.ttubeog.global.config.security.token.MemberPrincipal; import lombok.RequiredArgsConstructor; import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; @@ -37,21 +37,21 @@ public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2Aut private OAuth2User processOAuth2User(OAuth2UserRequest oAuth2UserRequest, OAuth2User oAuth2User) { OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(oAuth2UserRequest.getClientRegistration().getRegistrationId(), oAuth2User.getAttributes()); DefaultAssert.isAuthentication(!oAuth2UserInfo.getEmail().isEmpty()); - + Optional userOptional = memberRepository.findByEmail(oAuth2UserInfo.getEmail()); Member member; if(userOptional.isPresent()) { member = userOptional.get(); DefaultAssert.isAuthentication(member.getProvider().equals(Provider.valueOf(oAuth2UserRequest.getClientRegistration().getRegistrationId()))); - member = updateExistingUser(member, oAuth2UserInfo); + member = updateExistingMember(member, oAuth2UserInfo); } else { - member = registerNewUser(oAuth2UserRequest, oAuth2UserInfo); + member = registerNewMember(oAuth2UserRequest, oAuth2UserInfo); } - return UserPrincipal.create(member, oAuth2User.getAttributes()); + return MemberPrincipal.create(member, oAuth2User.getAttributes()); } - private Member registerNewUser(OAuth2UserRequest oAuth2UserRequest, OAuth2UserInfo oAuth2UserInfo) { + private Member registerNewMember(OAuth2UserRequest oAuth2UserRequest, OAuth2UserInfo oAuth2UserInfo) { Member member = Member.builder() .provider(Provider.valueOf(oAuth2UserRequest.getClientRegistration().getRegistrationId())) .providerId(oAuth2UserInfo.getId()) @@ -64,7 +64,7 @@ private Member registerNewUser(OAuth2UserRequest oAuth2UserRequest, OAuth2UserIn return memberRepository.save(member); } - private Member updateExistingUser(Member member, OAuth2UserInfo oAuth2UserInfo) { + private Member updateExistingMember(Member member, OAuth2UserInfo oAuth2UserInfo) { member.updateName(oAuth2UserInfo.getName()); member.updateImageUrl(oAuth2UserInfo.getImageUrl()); diff --git a/src/main/java/com/ttubeog/domain/auth/application/CustomUserDetailsService.java b/src/main/java/com/ttubeog/domain/auth/application/CustomMemberDetailsService.java similarity index 79% rename from src/main/java/com/ttubeog/domain/auth/application/CustomUserDetailsService.java rename to src/main/java/com/ttubeog/domain/auth/application/CustomMemberDetailsService.java index 59c10ed6..a8b63c67 100644 --- a/src/main/java/com/ttubeog/domain/auth/application/CustomUserDetailsService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/CustomMemberDetailsService.java @@ -3,7 +3,7 @@ import com.ttubeog.domain.member.domain.Member; import com.ttubeog.domain.member.domain.repository.MemberRepository; import com.ttubeog.global.DefaultAssert; -import com.ttubeog.global.config.security.token.UserPrincipal; +import com.ttubeog.global.config.security.token.MemberPrincipal; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.security.core.userdetails.UserDetails; @@ -15,7 +15,7 @@ @RequiredArgsConstructor @Service -public class CustomUserDetailsService implements UserDetailsService{ +public class CustomMemberDetailsService implements UserDetailsService{ private final MemberRepository memberRepository; @@ -24,10 +24,10 @@ public UserDetails loadUserByUsername(String email) throws UsernameNotFoundExcep Member member = memberRepository.findByEmail(email) .orElseThrow(() -> - new UsernameNotFoundException("유저 정보를 찾을 수 없습니다.") + new UsernameNotFoundException("멤버 정보를 찾을 수 없습니다.") ); - return UserPrincipal.create(member); + return MemberPrincipal.create(member); } @Transactional @@ -35,7 +35,7 @@ public UserDetails loadUserById(Long id) { Optional user = memberRepository.findById(id); DefaultAssert.isOptionalPresent(user); - return UserPrincipal.create(user.get()); + return MemberPrincipal.create(user.get()); } } diff --git a/src/main/java/com/ttubeog/domain/auth/application/CustomTokenProviderService.java b/src/main/java/com/ttubeog/domain/auth/application/CustomTokenProviderService.java index eba5acba..a6672c38 100644 --- a/src/main/java/com/ttubeog/domain/auth/application/CustomTokenProviderService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/CustomTokenProviderService.java @@ -2,7 +2,7 @@ import com.ttubeog.domain.auth.dto.TokenMapping; import com.ttubeog.global.config.security.OAuth2Config; -import com.ttubeog.global.config.security.token.UserPrincipal; +import com.ttubeog.global.config.security.token.MemberPrincipal; import io.jsonwebtoken.*; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; @@ -24,10 +24,10 @@ public class CustomTokenProviderService { private OAuth2Config oAuth2Config; @Autowired - private CustomUserDetailsService customUserDetailsService; + private CustomMemberDetailsService customMemberDetailsService; public TokenMapping refreshToken(Authentication authentication, String refreshToken) { - UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal(); + MemberPrincipal memberPrincipal = (MemberPrincipal) authentication.getPrincipal(); Date now = new Date(); Date accessTokenExpiresIn = new Date(now.getTime() + oAuth2Config.getAuth().getAccessTokenExpirationMsec()); @@ -37,21 +37,21 @@ public TokenMapping refreshToken(Authentication authentication, String refreshTo Key key = Keys.hmacShaKeyFor(keyBytes); String accessToken = Jwts.builder() - .setSubject(Long.toString(userPrincipal.getId())) + .setSubject(Long.toString(memberPrincipal.getId())) .setIssuedAt(new Date()) .setExpiration(accessTokenExpiresIn) .signWith(key, SignatureAlgorithm.HS512) .compact(); return TokenMapping.builder() - .userEmail(userPrincipal.getEmail()) + .userEmail(memberPrincipal.getEmail()) .accessToken(accessToken) .refreshToken(refreshToken) .build(); } public TokenMapping createToken(Authentication authentication) { - UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal(); + MemberPrincipal memberPrincipal = (MemberPrincipal) authentication.getPrincipal(); Date now = new Date(); @@ -64,7 +64,7 @@ public TokenMapping createToken(Authentication authentication) { Key key = Keys.hmacShaKeyFor(keyBytes); String accessToken = Jwts.builder() - .setSubject(Long.toString(userPrincipal.getId())) + .setSubject(Long.toString(memberPrincipal.getId())) .setIssuedAt(new Date()) .setExpiration(accessTokenExpiresIn) .signWith(key, SignatureAlgorithm.HS512) @@ -76,7 +76,7 @@ public TokenMapping createToken(Authentication authentication) { .compact(); return TokenMapping.builder() - .userEmail(userPrincipal.getEmail()) + .userEmail(memberPrincipal.getEmail()) .accessToken(accessToken) .refreshToken(refreshToken) .build(); @@ -94,13 +94,13 @@ public Long getUserIdFromToken(String token) { public UsernamePasswordAuthenticationToken getAuthenticationById(String token){ Long userId = getUserIdFromToken(token); - UserDetails userDetails = customUserDetailsService.loadUserById(userId); + UserDetails userDetails = customMemberDetailsService.loadUserById(userId); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); return authentication; } public UsernamePasswordAuthenticationToken getAuthenticationByEmail(String email){ - UserDetails userDetails = customUserDetailsService.loadUserByUsername(email); + UserDetails userDetails = customMemberDetailsService.loadUserByUsername(email); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); return authentication; } diff --git a/src/main/java/com/ttubeog/domain/auth/controller/OauthController.java b/src/main/java/com/ttubeog/domain/auth/controller/OauthController.java new file mode 100644 index 00000000..8d16e68b --- /dev/null +++ b/src/main/java/com/ttubeog/domain/auth/controller/OauthController.java @@ -0,0 +1,9 @@ +package com.ttubeog.domain.auth.controller; + +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequiredArgsConstructor +public class OauthController { +} diff --git a/src/main/java/com/ttubeog/domain/member/application/MemberService.java b/src/main/java/com/ttubeog/domain/member/application/MemberService.java index 943eee8f..b9cc6379 100644 --- a/src/main/java/com/ttubeog/domain/member/application/MemberService.java +++ b/src/main/java/com/ttubeog/domain/member/application/MemberService.java @@ -4,7 +4,7 @@ import com.ttubeog.domain.member.domain.Member; import com.ttubeog.domain.member.domain.repository.MemberRepository; import com.ttubeog.global.DefaultAssert; -import com.ttubeog.global.config.security.token.UserPrincipal; +import com.ttubeog.global.config.security.token.MemberPrincipal; import com.ttubeog.global.payload.ApiResponse; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; @@ -20,8 +20,8 @@ public class MemberService { private final MemberRepository memberRepository; // 현재 유저 조회 - public ResponseEntity getCurrentUser(UserPrincipal userPrincipal){ - Optional checkUser = memberRepository.findById(userPrincipal.getId()); + public ResponseEntity getCurrentUser(MemberPrincipal memberPrincipal){ + Optional checkUser = memberRepository.findById(memberPrincipal.getId()); DefaultAssert.isOptionalPresent(checkUser); Member member = checkUser.get(); diff --git a/src/main/java/com/ttubeog/domain/member/presentation/MemberController.java b/src/main/java/com/ttubeog/domain/member/presentation/MemberController.java index 787d6a9d..aa44a65f 100644 --- a/src/main/java/com/ttubeog/domain/member/presentation/MemberController.java +++ b/src/main/java/com/ttubeog/domain/member/presentation/MemberController.java @@ -2,8 +2,8 @@ import com.ttubeog.domain.member.application.MemberService; import com.ttubeog.domain.member.dto.response.MemberDetailRes; -import com.ttubeog.global.config.security.token.CurrentUser; -import com.ttubeog.global.config.security.token.UserPrincipal; +import com.ttubeog.global.config.security.token.CurrentMember; +import com.ttubeog.global.config.security.token.MemberPrincipal; import com.ttubeog.global.payload.ErrorResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -33,9 +33,9 @@ public class MemberController { }) @GetMapping public ResponseEntity getCurrentUser( - @Parameter(description = "Accesstoken을 입력해주세요.", required = true) @CurrentUser UserPrincipal userPrincipal + @Parameter(description = "Accesstoken을 입력해주세요.", required = true) @CurrentMember MemberPrincipal memberPrincipal ) { - return memberService.getCurrentUser(userPrincipal); + return memberService.getCurrentUser(memberPrincipal); } } diff --git a/src/main/java/com/ttubeog/global/config/security/SecurityConfig.java b/src/main/java/com/ttubeog/global/config/security/SecurityConfig.java index a602429a..a26ab307 100644 --- a/src/main/java/com/ttubeog/global/config/security/SecurityConfig.java +++ b/src/main/java/com/ttubeog/global/config/security/SecurityConfig.java @@ -1,7 +1,7 @@ package com.ttubeog.global.config.security; import com.ttubeog.domain.auth.application.CustomDefaultOAuth2UserService; -import com.ttubeog.domain.auth.application.CustomUserDetailsService; +import com.ttubeog.domain.auth.application.CustomMemberDetailsService; import com.ttubeog.domain.auth.domain.repository.CustomAuthorizationRequestRepository; import com.ttubeog.global.config.security.handler.CustomSimpleUrlAuthenticationFailureHandler; import com.ttubeog.global.config.security.handler.CustomSimpleUrlAuthenticationSuccessHandler; @@ -30,7 +30,7 @@ @EnableWebSecurity public class SecurityConfig { - private final CustomUserDetailsService customUserDetailsService; + private final CustomMemberDetailsService customMemberDetailsService; private final CustomDefaultOAuth2UserService customOAuth2UserService; private final CustomSimpleUrlAuthenticationSuccessHandler oAuth2AuthenticationSuccessHandler; private final CustomSimpleUrlAuthenticationFailureHandler oAuth2AuthenticationFailureHandler; @@ -50,7 +50,7 @@ public CustomOncePerRequestFilter customOncePerRequestFilter() { public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); - authenticationProvider.setUserDetailsService(customUserDetailsService); + authenticationProvider.setUserDetailsService(customMemberDetailsService); authenticationProvider.setPasswordEncoder(passwordEncoder()); return authenticationProvider; diff --git a/src/main/java/com/ttubeog/global/config/security/token/CurrentUser.java b/src/main/java/com/ttubeog/global/config/security/token/CurrentMember.java similarity index 89% rename from src/main/java/com/ttubeog/global/config/security/token/CurrentUser.java rename to src/main/java/com/ttubeog/global/config/security/token/CurrentMember.java index 5e48850c..ea1970da 100644 --- a/src/main/java/com/ttubeog/global/config/security/token/CurrentUser.java +++ b/src/main/java/com/ttubeog/global/config/security/token/CurrentMember.java @@ -8,6 +8,6 @@ @Retention(RetentionPolicy.RUNTIME) @Documented @AuthenticationPrincipal -public @interface CurrentUser { +public @interface CurrentMember { } diff --git a/src/main/java/com/ttubeog/global/config/security/token/UserPrincipal.java b/src/main/java/com/ttubeog/global/config/security/token/MemberPrincipal.java similarity index 80% rename from src/main/java/com/ttubeog/global/config/security/token/UserPrincipal.java rename to src/main/java/com/ttubeog/global/config/security/token/MemberPrincipal.java index afc6d046..e222aef5 100644 --- a/src/main/java/com/ttubeog/global/config/security/token/UserPrincipal.java +++ b/src/main/java/com/ttubeog/global/config/security/token/MemberPrincipal.java @@ -13,7 +13,7 @@ import java.util.Map; @Getter -public class UserPrincipal implements OAuth2User, UserDetails{ +public class MemberPrincipal implements OAuth2User, UserDetails{ private final Member member; @@ -23,7 +23,7 @@ public class UserPrincipal implements OAuth2User, UserDetails{ private final Collection authorities; private Map attributes; - public UserPrincipal(Member member, Long id, String email, String password, Collection authorities) { + public MemberPrincipal(Member member, Long id, String email, String password, Collection authorities) { this.member = member; this.id = id; this.email = email; @@ -31,9 +31,9 @@ public UserPrincipal(Member member, Long id, String email, String password, Coll this.authorities = authorities; } - public static UserPrincipal create(final Member member) { + public static MemberPrincipal create(final Member member) { List authorities = Collections.singletonList(new SimpleGrantedAuthority(member.getRole().getValue())); - return new UserPrincipal( + return new MemberPrincipal( member, member.getId(), member.getEmail(), @@ -42,10 +42,10 @@ public static UserPrincipal create(final Member member) { ); } - public static UserPrincipal create(Member member, Map attributes) { - UserPrincipal userPrincipal = UserPrincipal.create(member); - userPrincipal.setAttributes(attributes); - return userPrincipal; + public static MemberPrincipal create(Member member, Map attributes) { + MemberPrincipal memberPrincipal = MemberPrincipal.create(member); + memberPrincipal.setAttributes(attributes); + return memberPrincipal; } public void setAttributes(Map attributes) { From 8db6adb995125a0bf68a9a2818b15dd56b3c3e67 Mon Sep 17 00:00:00 2001 From: arinming Date: Tue, 16 Jan 2024 17:53:37 +0900 Subject: [PATCH 02/12] =?UTF-8?q?[FEAT]=20JWT=EB=A5=BC=20=ED=86=B5?= =?UTF-8?q?=ED=95=9C=20accessToken,=20refreshToken=20=EC=83=9D=EC=84=B1=20?= =?UTF-8?q?=EB=A1=9C=EC=A7=81=20=EC=B6=94=EA=B0=80=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../domain/auth/service/JwtTokenService.java | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 src/main/java/com/ttubeog/domain/auth/service/JwtTokenService.java diff --git a/src/main/java/com/ttubeog/domain/auth/service/JwtTokenService.java b/src/main/java/com/ttubeog/domain/auth/service/JwtTokenService.java new file mode 100644 index 00000000..8c29a7e8 --- /dev/null +++ b/src/main/java/com/ttubeog/domain/auth/service/JwtTokenService.java @@ -0,0 +1,86 @@ +package com.ttubeog.domain.auth.service; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.io.Decoders; +import io.jsonwebtoken.io.Encoders; +import io.jsonwebtoken.security.Keys; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.nio.charset.StandardCharsets; +import java.security.Key; +import java.util.Date; +import java.util.Random; + +@Service +public class JwtTokenService implements InitializingBean { + + private final String secretKey; + private final long accessTokenExpirationInSeconds; + private final long refreshTokenExpirationInSeconds; + private static Key key; + + + public JwtTokenService( + @Value("${jwt.secret-key}") String secretKey, + @Value("${jwt.access-expired-time}") long accessTokenExpirationInSeconds, + @Value("${jwt.refresh-expired-time}") long refreshTokenExpirationInSeconds + ) { + this.secretKey = secretKey; + this.accessTokenExpirationInSeconds = accessTokenExpirationInSeconds; + this.refreshTokenExpirationInSeconds = refreshTokenExpirationInSeconds; + } + + @Override + public void afterPropertiesSet() throws Exception { + key = getKeyFromBase64EncodedKey(encodeBase64SecretKey(secretKey)); + } + + // JWT 토큰 생성 + public String createToken(String payload, long expireLength) { + // 토큰에 포함될 정보 + Claims claims = Jwts.claims().setSubject(payload); + // 현재 날짜와 시간 + Date now = new Date(); + // 유효기간 + Date validity = new Date(now.getTime() + expireLength); + + return Jwts.builder() + .setClaims(claims) + .setIssuedAt(now) + .setExpiration(validity) + .signWith(key, SignatureAlgorithm.HS256) // 토큰 서명 + .compact(); + } + + // 액세스 토큰 생성 + public String createAccessToken(String payload) { + return createToken(payload, accessTokenExpirationInSeconds); + } + + // 리프레시 토큰 생성 + public String createRefreshToken() { + byte[] array = new byte[7]; + new Random().nextBytes(array); + String newPayload = new String(array, StandardCharsets.UTF_8); + + return createToken(newPayload, refreshTokenExpirationInSeconds); + } + + + + private String encodeBase64SecretKey(String secretKey) { + return Encoders.BASE64.encode(secretKey.getBytes(StandardCharsets.UTF_8)); + } + + private Key getKeyFromBase64EncodedKey(String encodedSecretKey) { + byte[] keyBytes = Decoders.BASE64.decode(encodedSecretKey); + + Key key = Keys.hmacShaKeyFor(keyBytes); + + return key; + } +} From d248648c8fc439d7ed08468333c2d7a8d00f252c Mon Sep 17 00:00:00 2001 From: arinming Date: Wed, 17 Jan 2024 02:49:19 +0900 Subject: [PATCH 03/12] =?UTF-8?q?[FEAT]=20KaKao=20=EC=A0=95=EB=B3=B4=20?= =?UTF-8?q?=EA=B0=80=EC=A0=B8=EC=98=A4=EB=8A=94=20=EB=A1=9C=EC=A7=81=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20=EB=B0=8F=20=EC=B9=B4=EC=B9=B4=EC=98=A4=20?= =?UTF-8?q?Dto=20=EC=83=9D=EC=84=B1=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 2 ++ .../JwtTokenService.java | 2 +- .../auth/application/KakaoOauthService.java | 28 +++++++++++++++++++ .../ttubeog/domain/auth/dto/KakaoInfoDto.java | 19 +++++++++++++ 4 files changed, 50 insertions(+), 1 deletion(-) rename src/main/java/com/ttubeog/domain/auth/{service => application}/JwtTokenService.java (98%) create mode 100644 src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java create mode 100644 src/main/java/com/ttubeog/domain/auth/dto/KakaoInfoDto.java diff --git a/build.gradle b/build.gradle index eb5a9b8c..7e687490 100644 --- a/build.gradle +++ b/build.gradle @@ -18,6 +18,8 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.springframework.boot:spring-boot-starter-webflux' + implementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-ui', version: '2.3.0' testImplementation group: 'org.springdoc', name: 'springdoc-openapi-starter-webmvc-api', version: '2.3.0' diff --git a/src/main/java/com/ttubeog/domain/auth/service/JwtTokenService.java b/src/main/java/com/ttubeog/domain/auth/application/JwtTokenService.java similarity index 98% rename from src/main/java/com/ttubeog/domain/auth/service/JwtTokenService.java rename to src/main/java/com/ttubeog/domain/auth/application/JwtTokenService.java index 8c29a7e8..a35090fe 100644 --- a/src/main/java/com/ttubeog/domain/auth/service/JwtTokenService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/JwtTokenService.java @@ -1,4 +1,4 @@ -package com.ttubeog.domain.auth.service; +package com.ttubeog.domain.auth.application; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; diff --git a/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java b/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java new file mode 100644 index 00000000..fb86ab0d --- /dev/null +++ b/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java @@ -0,0 +1,28 @@ +package com.ttubeog.domain.auth.application; + + +import com.ttubeog.domain.member.application.MemberService; +import lombok.RequiredArgsConstructor; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.stereotype.Service; +import org.springframework.web.reactive.function.client.WebClient; + +import java.util.Map; + +@RequiredArgsConstructor +@Service +public class KakaoOauthService { + private final MemberService memberService; + + // 카카오 API를 호출해서 AccessToken으로 멤버 정보를 가져오는 로직 + public Map getMemberInfoByToken(String accessToken) { + return WebClient.create() + .get() + .uri("https://kapi.kakao.com/v2/user/me") + .headers(httpHeaders -> httpHeaders.setBasicAuth(accessToken)) + .retrieve() + .bodyToMono(new ParameterizedTypeReference>() { + }) + .block(); + } +} diff --git a/src/main/java/com/ttubeog/domain/auth/dto/KakaoInfoDto.java b/src/main/java/com/ttubeog/domain/auth/dto/KakaoInfoDto.java new file mode 100644 index 00000000..e4eb653d --- /dev/null +++ b/src/main/java/com/ttubeog/domain/auth/dto/KakaoInfoDto.java @@ -0,0 +1,19 @@ +package com.ttubeog.domain.auth.dto; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +import java.util.Map; + +@Getter +@AllArgsConstructor +public class KakaoInfoDto { + private Long id; + private String email; + + public KakaoInfoDto(Map info) { + this.id = Long.valueOf(info.get("id").toString()); + this.email = info.get("email") != null + ? info.get(email).toString() : ""; + } +} From 37b2362dcbb4b229b625253a9fb60a0d74ae759b Mon Sep 17 00:00:00 2001 From: arinming Date: Wed, 17 Jan 2024 03:05:51 +0900 Subject: [PATCH 04/12] =?UTF-8?q?[FEAT]=20KaKao=20=EC=A0=95=EB=B3=B4?= =?UTF-8?q?=EB=A5=BC=20DB=EC=97=90=20=EC=A0=80=EC=9E=A5=ED=95=98=EB=8A=94?= =?UTF-8?q?=20=EB=A1=9C=EC=A7=81=20=EC=B6=94=EA=B0=80=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/application/KakaoOauthService.java | 20 +++++++++++++++++++ .../member/application/MemberService.java | 12 +++++++++++ 2 files changed, 32 insertions(+) diff --git a/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java b/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java index fb86ab0d..60c52773 100644 --- a/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java @@ -1,7 +1,9 @@ package com.ttubeog.domain.auth.application; +import com.ttubeog.domain.auth.dto.KakaoInfoDto; import com.ttubeog.domain.member.application.MemberService; +import com.ttubeog.domain.member.dto.response.MemberDetailRes; import lombok.RequiredArgsConstructor; import org.springframework.core.ParameterizedTypeReference; import org.springframework.stereotype.Service; @@ -25,4 +27,22 @@ public Map getMemberInfoByToken(String accessToken) { }) .block(); } + + + // 카카오 API에서 가져온 멤버 정보를 DB 저장, 업데이트 + public MemberDetailRes getMemberProfileByToken(String accessToken) { + Map memberInfoByToken = getMemberInfoByToken(accessToken); + KakaoInfoDto kakaoInfoDto = new KakaoInfoDto(memberInfoByToken); + MemberDetailRes memberDetailRes = MemberDetailRes.builder() + .id(kakaoInfoDto.getId()) + .email(kakaoInfoDto.getEmail()) + .build(); + + if(memberService.findById(memberDetailRes.getId()).isPresent()) { + memberService.update(memberDetailRes); + } else { + memberService.save(memberDetailRes); + } + return memberDetailRes; + } } diff --git a/src/main/java/com/ttubeog/domain/member/application/MemberService.java b/src/main/java/com/ttubeog/domain/member/application/MemberService.java index b9cc6379..30409aef 100644 --- a/src/main/java/com/ttubeog/domain/member/application/MemberService.java +++ b/src/main/java/com/ttubeog/domain/member/application/MemberService.java @@ -40,4 +40,16 @@ public ResponseEntity getCurrentUser(MemberPrincipal memberPrincipal){ return ResponseEntity.ok(apiResponse); } + public Optional findById(Long id) { + return memberRepository.findById(id); + } + + public void update(MemberDetailRes memberDetailRes) { + + } + + public void save(MemberDetailRes memberDetailRes) { + + } + } From e0af9ec5c773839a8de05183c5a17e4202b9fc92 Mon Sep 17 00:00:00 2001 From: arinming Date: Wed, 17 Jan 2024 18:49:08 +0900 Subject: [PATCH 05/12] =?UTF-8?q?[FEAT]=20MemberDto=20=EC=83=9D=EC=84=B1?= =?UTF-8?q?=20=EB=B0=8F=20OauthService=20=EB=A1=9C=EC=A7=81=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/application/KakaoOauthService.java | 14 ++++---- .../domain/auth/application/OauthService.java | 36 +++++++++++++++++++ .../member/application/MemberService.java | 15 +++++--- .../ttubeog/domain/member/domain/Member.java | 5 ++- .../ttubeog/domain/member/dto/MemberDto.java | 28 +++++++++++++++ 5 files changed, 87 insertions(+), 11 deletions(-) create mode 100644 src/main/java/com/ttubeog/domain/auth/application/OauthService.java create mode 100644 src/main/java/com/ttubeog/domain/member/dto/MemberDto.java diff --git a/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java b/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java index 60c52773..39266621 100644 --- a/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java @@ -3,6 +3,7 @@ import com.ttubeog.domain.auth.dto.KakaoInfoDto; import com.ttubeog.domain.member.application.MemberService; +import com.ttubeog.domain.member.dto.MemberDto; import com.ttubeog.domain.member.dto.response.MemberDetailRes; import lombok.RequiredArgsConstructor; import org.springframework.core.ParameterizedTypeReference; @@ -30,19 +31,20 @@ public Map getMemberInfoByToken(String accessToken) { // 카카오 API에서 가져온 멤버 정보를 DB 저장, 업데이트 - public MemberDetailRes getMemberProfileByToken(String accessToken) { + public MemberDto getMemberProfileByToken(String accessToken) { Map memberInfoByToken = getMemberInfoByToken(accessToken); KakaoInfoDto kakaoInfoDto = new KakaoInfoDto(memberInfoByToken); - MemberDetailRes memberDetailRes = MemberDetailRes.builder() + MemberDto memberDto = MemberDto.builder() .id(kakaoInfoDto.getId()) .email(kakaoInfoDto.getEmail()) + .platform("kakao") .build(); - if(memberService.findById(memberDetailRes.getId()).isPresent()) { - memberService.update(memberDetailRes); + if(memberService.findById(memberDto.getId()) != null) { + memberService.update(memberDto); } else { - memberService.save(memberDetailRes); + memberService.save(memberDto); } - return memberDetailRes; + return memberDto; } } diff --git a/src/main/java/com/ttubeog/domain/auth/application/OauthService.java b/src/main/java/com/ttubeog/domain/auth/application/OauthService.java new file mode 100644 index 00000000..5bec71e7 --- /dev/null +++ b/src/main/java/com/ttubeog/domain/auth/application/OauthService.java @@ -0,0 +1,36 @@ +package com.ttubeog.domain.auth.application; + +import com.ttubeog.domain.member.application.MemberService; +import com.ttubeog.domain.member.domain.Member; +import com.ttubeog.domain.member.dto.MemberDto; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; + +import java.util.Optional; + +@RequiredArgsConstructor +@Service +public class OauthService { + private final MemberService memberService; + private final JwtTokenService jwtTokenService; + private final KakaoOauthService kakaoOauthService; + + // 카카오 로그인 + public String loginWithKakao(String accessToken, HttpServletResponse response) { + MemberDto memberDto = kakaoOauthService.getMemberProfileByToken(accessToken); + return getTokens(memberDto.getId(), response); + } + + // 액세스, 리프레시 토큰 생성 + public String getTokens(Long id, HttpServletResponse response) { + final String accessToken = jwtTokenService.createAccessToken(id.toString()); + final String refreshToken = jwtTokenService.createRefreshToken(); + + MemberDto memberDto = memberService.findById(id); + memberDto.setRefreshToken(refreshToken); + memberService.updateRefreshToken(memberDto); + + return accessToken; + } +} diff --git a/src/main/java/com/ttubeog/domain/member/application/MemberService.java b/src/main/java/com/ttubeog/domain/member/application/MemberService.java index 30409aef..a79ec70b 100644 --- a/src/main/java/com/ttubeog/domain/member/application/MemberService.java +++ b/src/main/java/com/ttubeog/domain/member/application/MemberService.java @@ -1,5 +1,6 @@ package com.ttubeog.domain.member.application; +import com.ttubeog.domain.member.dto.MemberDto; import com.ttubeog.domain.member.dto.response.MemberDetailRes; import com.ttubeog.domain.member.domain.Member; import com.ttubeog.domain.member.domain.repository.MemberRepository; @@ -40,16 +41,22 @@ public ResponseEntity getCurrentUser(MemberPrincipal memberPrincipal){ return ResponseEntity.ok(apiResponse); } - public Optional findById(Long id) { - return memberRepository.findById(id); + public MemberDto findById(Long id) { + Optional optionalMember = memberRepository.findById(id); + + return optionalMember.map(MemberDto::toEntity).orElse(null); } - public void update(MemberDetailRes memberDetailRes) { + + public void save(MemberDto memberDetailRes) { } - public void save(MemberDetailRes memberDetailRes) { + public void update(MemberDto memberDetailRes) { + + } + public void updateRefreshToken(MemberDto memberDetailRes) { } } diff --git a/src/main/java/com/ttubeog/domain/member/domain/Member.java b/src/main/java/com/ttubeog/domain/member/domain/Member.java index 2b2b3a1b..da6b439e 100644 --- a/src/main/java/com/ttubeog/domain/member/domain/Member.java +++ b/src/main/java/com/ttubeog/domain/member/domain/Member.java @@ -33,8 +33,10 @@ public class Member extends BaseEntity { private String providerId; + private String platform; + @Builder - public Member(Long id, String name, String email, String imageUrl, Boolean emailVerified, String password, Provider provider, Role role, String providerId) { + public Member(Long id, String name, String email, String imageUrl, Boolean emailVerified, String password, Provider provider, Role role, String providerId, String platform) { this.id = id; this.name = name; this.email = email; @@ -43,6 +45,7 @@ public Member(Long id, String name, String email, String imageUrl, Boolean email this.provider = provider; this.role = role; this.providerId = providerId; + this.platform = platform; } public void updateName(String name){ diff --git a/src/main/java/com/ttubeog/domain/member/dto/MemberDto.java b/src/main/java/com/ttubeog/domain/member/dto/MemberDto.java new file mode 100644 index 00000000..9eefaa7d --- /dev/null +++ b/src/main/java/com/ttubeog/domain/member/dto/MemberDto.java @@ -0,0 +1,28 @@ +package com.ttubeog.domain.member.dto; + +import com.ttubeog.domain.member.domain.Member; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +@Builder +@AllArgsConstructor +public class MemberDto { + private Long id; + private String email; + private String name; + private String platform; + private String refreshToken; + + public static MemberDto toEntity(Member member) { + return MemberDto.builder() + .id(member.getId()) + .email(member.getEmail()) + .name(member.getName()) + .platform(member.getPlatform()) + .build(); + } +} From 039096d382cf58fb717e03f36f9b0bfe0b0ef70f Mon Sep 17 00:00:00 2001 From: arinming Date: Wed, 17 Jan 2024 19:43:18 +0900 Subject: [PATCH 06/12] =?UTF-8?q?[FEAT]=20Refresh=20Token=20=EA=B0=B1?= =?UTF-8?q?=EC=8B=A0=20=EB=A1=9C=EC=A7=81=20=EC=B6=94=EA=B0=80=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../domain/auth/application/KakaoOauthService.java | 1 - .../domain/auth/application/OauthService.java | 14 +++++++++++--- .../domain/member/application/MemberService.java | 8 ++++++-- .../member/domain/repository/MemberRepository.java | 7 +++++-- 4 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java b/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java index 39266621..864c7e0b 100644 --- a/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/KakaoOauthService.java @@ -4,7 +4,6 @@ import com.ttubeog.domain.auth.dto.KakaoInfoDto; import com.ttubeog.domain.member.application.MemberService; import com.ttubeog.domain.member.dto.MemberDto; -import com.ttubeog.domain.member.dto.response.MemberDetailRes; import lombok.RequiredArgsConstructor; import org.springframework.core.ParameterizedTypeReference; import org.springframework.stereotype.Service; diff --git a/src/main/java/com/ttubeog/domain/auth/application/OauthService.java b/src/main/java/com/ttubeog/domain/auth/application/OauthService.java index 5bec71e7..1f436923 100644 --- a/src/main/java/com/ttubeog/domain/auth/application/OauthService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/OauthService.java @@ -1,14 +1,11 @@ package com.ttubeog.domain.auth.application; import com.ttubeog.domain.member.application.MemberService; -import com.ttubeog.domain.member.domain.Member; import com.ttubeog.domain.member.dto.MemberDto; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; -import java.util.Optional; - @RequiredArgsConstructor @Service public class OauthService { @@ -33,4 +30,15 @@ public String getTokens(Long id, HttpServletResponse response) { return accessToken; } + + // 리프레시 토큰을 액세스 토큰으로 갱신 + public String refreshToAccessToken(String refreshToken) { + MemberDto memberDto = memberService.findByRefreshToken(refreshToken); + + if(memberDto == null) { + + } + + return jwtTokenService.createAccessToken(memberDto.getId().toString()); + } } diff --git a/src/main/java/com/ttubeog/domain/member/application/MemberService.java b/src/main/java/com/ttubeog/domain/member/application/MemberService.java index a79ec70b..4aa7d84c 100644 --- a/src/main/java/com/ttubeog/domain/member/application/MemberService.java +++ b/src/main/java/com/ttubeog/domain/member/application/MemberService.java @@ -42,11 +42,15 @@ public ResponseEntity getCurrentUser(MemberPrincipal memberPrincipal){ } public MemberDto findById(Long id) { - Optional optionalMember = memberRepository.findById(id); + Optional member = memberRepository.findById(id); - return optionalMember.map(MemberDto::toEntity).orElse(null); + return member.map(MemberDto::toEntity).orElse(null); } + public MemberDto findByRefreshToken(String refreshToken) { + Optional member = memberRepository.findByRefreshToken(refreshToken); + return member.map(MemberDto::toEntity).orElse(null); + } public void save(MemberDto memberDetailRes) { diff --git a/src/main/java/com/ttubeog/domain/member/domain/repository/MemberRepository.java b/src/main/java/com/ttubeog/domain/member/domain/repository/MemberRepository.java index 78b88eaa..c4b61a5e 100644 --- a/src/main/java/com/ttubeog/domain/member/domain/repository/MemberRepository.java +++ b/src/main/java/com/ttubeog/domain/member/domain/repository/MemberRepository.java @@ -1,6 +1,7 @@ package com.ttubeog.domain.member.domain.repository; import com.ttubeog.domain.member.domain.Member; +import com.ttubeog.domain.member.dto.MemberDto; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @@ -8,8 +9,10 @@ @Repository public interface MemberRepository extends JpaRepository{ - + Optional findByEmail(String email); - Boolean existsByEmail(String email); + Optional findByRefreshToken(String refreshToken); + + Boolean existsByEmail(String email); } From 1fde5de7092150793a3048ba0ff7f4be9c187b74 Mon Sep 17 00:00:00 2001 From: arinming Date: Wed, 17 Jan 2024 19:50:41 +0900 Subject: [PATCH 07/12] =?UTF-8?q?[FEAT]=20=ED=86=A0=ED=81=B0=20=EA=B4=80?= =?UTF-8?q?=EB=A0=A8=20DTO=20=EC=B6=94=EA=B0=80=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../domain/auth/controller/OauthController.java | 4 ++++ .../com/ttubeog/domain/auth/dto/OauthRequestDto.java | 8 ++++++++ .../com/ttubeog/domain/auth/dto/OauthResponseDto.java | 10 ++++++++++ .../domain/auth/dto/RefreshTokenResponseDto.java | 11 +++++++++++ .../member/domain/repository/MemberRepository.java | 1 - 5 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/ttubeog/domain/auth/dto/OauthRequestDto.java create mode 100644 src/main/java/com/ttubeog/domain/auth/dto/OauthResponseDto.java create mode 100644 src/main/java/com/ttubeog/domain/auth/dto/RefreshTokenResponseDto.java diff --git a/src/main/java/com/ttubeog/domain/auth/controller/OauthController.java b/src/main/java/com/ttubeog/domain/auth/controller/OauthController.java index 8d16e68b..4c2a3e91 100644 --- a/src/main/java/com/ttubeog/domain/auth/controller/OauthController.java +++ b/src/main/java/com/ttubeog/domain/auth/controller/OauthController.java @@ -1,9 +1,13 @@ package com.ttubeog.domain.auth.controller; +import com.ttubeog.domain.auth.application.OauthService; import lombok.RequiredArgsConstructor; +import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequiredArgsConstructor public class OauthController { + private final OauthService oauthService; } diff --git a/src/main/java/com/ttubeog/domain/auth/dto/OauthRequestDto.java b/src/main/java/com/ttubeog/domain/auth/dto/OauthRequestDto.java new file mode 100644 index 00000000..7b7ea9b0 --- /dev/null +++ b/src/main/java/com/ttubeog/domain/auth/dto/OauthRequestDto.java @@ -0,0 +1,8 @@ +package com.ttubeog.domain.auth.dto; + +import lombok.Getter; + +@Getter +public class OauthRequestDto { + private String accessToken; +} diff --git a/src/main/java/com/ttubeog/domain/auth/dto/OauthResponseDto.java b/src/main/java/com/ttubeog/domain/auth/dto/OauthResponseDto.java new file mode 100644 index 00000000..c5d3ddd8 --- /dev/null +++ b/src/main/java/com/ttubeog/domain/auth/dto/OauthResponseDto.java @@ -0,0 +1,10 @@ +package com.ttubeog.domain.auth.dto; + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class OauthResponseDto { + private String accessToken; +} diff --git a/src/main/java/com/ttubeog/domain/auth/dto/RefreshTokenResponseDto.java b/src/main/java/com/ttubeog/domain/auth/dto/RefreshTokenResponseDto.java new file mode 100644 index 00000000..dfaa7798 --- /dev/null +++ b/src/main/java/com/ttubeog/domain/auth/dto/RefreshTokenResponseDto.java @@ -0,0 +1,11 @@ +package com.ttubeog.domain.auth.dto; + + +import lombok.Getter; +import lombok.Setter; + +@Getter +@Setter +public class RefreshTokenResponseDto { + private String accessToken; +} diff --git a/src/main/java/com/ttubeog/domain/member/domain/repository/MemberRepository.java b/src/main/java/com/ttubeog/domain/member/domain/repository/MemberRepository.java index c4b61a5e..258d5acb 100644 --- a/src/main/java/com/ttubeog/domain/member/domain/repository/MemberRepository.java +++ b/src/main/java/com/ttubeog/domain/member/domain/repository/MemberRepository.java @@ -1,7 +1,6 @@ package com.ttubeog.domain.member.domain.repository; import com.ttubeog.domain.member.domain.Member; -import com.ttubeog.domain.member.dto.MemberDto; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; From a7d1a51f445d87d7d934e79b638b1dfadd035648 Mon Sep 17 00:00:00 2001 From: arinming Date: Wed, 17 Jan 2024 20:01:01 +0900 Subject: [PATCH 08/12] =?UTF-8?q?[FEAT]=20=EC=B9=B4=EC=B9=B4=EC=98=A4=20?= =?UTF-8?q?=EB=A1=9C=EA=B7=B8=EC=9D=B8=20=EC=BB=A8=ED=8A=B8=EB=A1=A4?= =?UTF-8?q?=EB=9F=AC=20=EA=B5=AC=ED=98=84=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../domain/auth/controller/OauthController.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/main/java/com/ttubeog/domain/auth/controller/OauthController.java b/src/main/java/com/ttubeog/domain/auth/controller/OauthController.java index 4c2a3e91..0e505a56 100644 --- a/src/main/java/com/ttubeog/domain/auth/controller/OauthController.java +++ b/src/main/java/com/ttubeog/domain/auth/controller/OauthController.java @@ -1,13 +1,30 @@ package com.ttubeog.domain.auth.controller; import com.ttubeog.domain.auth.application.OauthService; +import com.ttubeog.domain.auth.dto.OauthRequestDto; +import com.ttubeog.domain.auth.dto.OauthResponseDto; +import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse; import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequiredArgsConstructor public class OauthController { private final OauthService oauthService; + + // 카카오 로그인 + @PostMapping("/auth/login/kakao") + public OauthResponseDto loginWithKaKao( + @RequestBody + OauthRequestDto oauthRequestDto, + HttpServletResponse response + ) { + OauthResponseDto oauthResponseDto = new OauthResponseDto(); + String accessToken = oauthService.loginWithKakao(oauthResponseDto.getAccessToken(), response); + oauthResponseDto.setAccessToken(accessToken); + return oauthResponseDto; + } } From 9d424b389af003cd74c4f882949c9505e8794f12 Mon Sep 17 00:00:00 2001 From: arinming Date: Wed, 17 Jan 2024 20:18:15 +0900 Subject: [PATCH 09/12] =?UTF-8?q?[FEAT]=20=ED=86=A0=ED=81=B0=EC=9D=84=20?= =?UTF-8?q?=EC=BF=A0=ED=82=A4=EC=97=90=20=EC=A0=80=EC=9E=A5=ED=95=98?= =?UTF-8?q?=EB=8A=94=20=EB=A1=9C=EC=A7=81=20=EC=B6=94=EA=B0=80=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/application/JwtTokenService.java | 25 +++++++++++++++++++ .../member/presentation/MemberController.java | 8 +++--- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/ttubeog/domain/auth/application/JwtTokenService.java b/src/main/java/com/ttubeog/domain/auth/application/JwtTokenService.java index a35090fe..0e22724f 100644 --- a/src/main/java/com/ttubeog/domain/auth/application/JwtTokenService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/JwtTokenService.java @@ -1,11 +1,14 @@ package com.ttubeog.domain.auth.application; import io.jsonwebtoken.Claims; +import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders; import io.jsonwebtoken.security.Keys; +import jakarta.servlet.http.Cookie; +import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @@ -70,6 +73,18 @@ public String createRefreshToken() { return createToken(newPayload, refreshTokenExpirationInSeconds); } + public String getPayload(String token) { + try { + return Jwts.parserBuilder() + .setSigningKey(key) + .build() + .parseClaimsJws(token) + .getBody() + .getSubject(); + } catch (ExpiredJwtException e) { + return e.getClaims().getSubject(); + } + } private String encodeBase64SecretKey(String secretKey) { @@ -83,4 +98,14 @@ private Key getKeyFromBase64EncodedKey(String encodedSecretKey) { return key; } + + // 클라이언트 쿠키에 리프레시 토큰을 저장 + public void addRefreshTokenToCookie(String refreshToken, HttpServletResponse response) { + Long age = refreshTokenExpirationInSeconds; + Cookie cookie = new Cookie("refresh_token", refreshToken); + cookie.setPath("/"); + cookie.setMaxAge(age.intValue()); + cookie.setHttpOnly(true); + response.addCookie(cookie); + } } diff --git a/src/main/java/com/ttubeog/domain/member/presentation/MemberController.java b/src/main/java/com/ttubeog/domain/member/presentation/MemberController.java index aa44a65f..d31faba5 100644 --- a/src/main/java/com/ttubeog/domain/member/presentation/MemberController.java +++ b/src/main/java/com/ttubeog/domain/member/presentation/MemberController.java @@ -26,13 +26,13 @@ public class MemberController { private final MemberService memberService; - @Operation(summary = "유저 정보 확인", description = "현재 접속된 유저정보를 확인합니다.") + @Operation(summary = "멤버 정보 확인", description = "현재 접속된 멤버 정보를 확인합니다.") @ApiResponses(value = { - @ApiResponse(responseCode = "200", description = "유저 확인 성공", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = MemberDetailRes.class) ) } ), - @ApiResponse(responseCode = "400", description = "유저 확인 실패", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class) ) } ), + @ApiResponse(responseCode = "200", description = "멤버 확인 성공", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = MemberDetailRes.class) ) } ), + @ApiResponse(responseCode = "400", description = "멤버 확인 실패", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class) ) } ), }) @GetMapping - public ResponseEntity getCurrentUser( + public ResponseEntity getCurrentMember( @Parameter(description = "Accesstoken을 입력해주세요.", required = true) @CurrentMember MemberPrincipal memberPrincipal ) { return memberService.getCurrentUser(memberPrincipal); From ed76baf999f7a1f895486ad0d3dae561d592effb Mon Sep 17 00:00:00 2001 From: arinming Date: Thu, 18 Jan 2024 14:24:53 +0900 Subject: [PATCH 10/12] =?UTF-8?q?[FEAT]=20SecurityConfig=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../domain/auth/config/SecurityConfig.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/main/java/com/ttubeog/domain/auth/config/SecurityConfig.java diff --git a/src/main/java/com/ttubeog/domain/auth/config/SecurityConfig.java b/src/main/java/com/ttubeog/domain/auth/config/SecurityConfig.java new file mode 100644 index 00000000..3d237ec8 --- /dev/null +++ b/src/main/java/com/ttubeog/domain/auth/config/SecurityConfig.java @@ -0,0 +1,41 @@ +package com.ttubeog.domain.auth.config; + +import com.ttubeog.domain.auth.application.JwtTokenService; +import com.ttubeog.domain.member.application.MemberService; +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.web.SecurityFilterChain; + +import static org.springframework.security.config.Customizer.withDefaults; + +@RequiredArgsConstructor +@Configuration +public class SecurityConfig { + private final JwtTokenService jwtTokenService; + private final MemberService memberService; + + @Bean + public AuthenticationManager authenticationManager( + final AuthenticationConfiguration authenticationConfiguration + ) throws Exception { + return authenticationConfiguration.getAuthenticationManager(); + } + + @Bean + public SecurityFilterChain configure(final HttpSecurity httpSecurity) throws Exception { + return httpSecurity.cors(withDefaults()) + .csrf((csrf) -> csrf.disable()) + .authorizeHttpRequests((authorize) -> authorize + .requestMatchers("/auth/login/**", "/token/refresh").permitAll() + .anyRequest().authenticated()) + .sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.disable()) // 기본 로그인 폼 미사용 + .httpBasic(httpSecurityHttpBasicConfigurer -> httpSecurityHttpBasicConfigurer.disable()) // 기본 http 미사용 + .build(); + } +} From 591b448fae71ab27007d391992b93ca349399609 Mon Sep 17 00:00:00 2001 From: arinming Date: Thu, 18 Jan 2024 14:55:53 +0900 Subject: [PATCH 11/12] =?UTF-8?q?[FEAT]=20JWT=20=ED=95=84=ED=84=B0=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/application/JwtTokenService.java | 17 +++++-- .../domain/auth/config/SecurityConfig.java | 3 ++ .../ttubeog/domain/auth/filter/JwtFilter.java | 47 +++++++++++++++++++ 3 files changed, 63 insertions(+), 4 deletions(-) create mode 100644 src/main/java/com/ttubeog/domain/auth/filter/JwtFilter.java diff --git a/src/main/java/com/ttubeog/domain/auth/application/JwtTokenService.java b/src/main/java/com/ttubeog/domain/auth/application/JwtTokenService.java index 0e22724f..c9246c54 100644 --- a/src/main/java/com/ttubeog/domain/auth/application/JwtTokenService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/JwtTokenService.java @@ -1,9 +1,6 @@ package com.ttubeog.domain.auth.application; -import io.jsonwebtoken.Claims; -import io.jsonwebtoken.ExpiredJwtException; -import io.jsonwebtoken.Jwts; -import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.*; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.io.Encoders; import io.jsonwebtoken.security.Keys; @@ -86,6 +83,18 @@ public String getPayload(String token) { } } + public boolean validateToken(String token) { + try { + Jws claimsJws = Jwts.parserBuilder() + .setSigningKey(key) + .build() + .parseClaimsJws(token); + return !claimsJws.getBody().getExpiration().before(new Date()); + } catch (JwtException | IllegalArgumentException exception) { + return false; + } + } + private String encodeBase64SecretKey(String secretKey) { return Encoders.BASE64.encode(secretKey.getBytes(StandardCharsets.UTF_8)); diff --git a/src/main/java/com/ttubeog/domain/auth/config/SecurityConfig.java b/src/main/java/com/ttubeog/domain/auth/config/SecurityConfig.java index 3d237ec8..4e255c55 100644 --- a/src/main/java/com/ttubeog/domain/auth/config/SecurityConfig.java +++ b/src/main/java/com/ttubeog/domain/auth/config/SecurityConfig.java @@ -1,6 +1,7 @@ package com.ttubeog.domain.auth.config; import com.ttubeog.domain.auth.application.JwtTokenService; +import com.ttubeog.domain.auth.filter.JwtFilter; import com.ttubeog.domain.member.application.MemberService; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; @@ -10,6 +11,7 @@ import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import static org.springframework.security.config.Customizer.withDefaults; @@ -36,6 +38,7 @@ public SecurityFilterChain configure(final HttpSecurity httpSecurity) throws Exc .sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.disable()) // 기본 로그인 폼 미사용 .httpBasic(httpSecurityHttpBasicConfigurer -> httpSecurityHttpBasicConfigurer.disable()) // 기본 http 미사용 + .addFilterBefore(new JwtFilter(jwtTokenService, memberService), UsernamePasswordAuthenticationFilter.class) // JWT 필터 추가 .build(); } } diff --git a/src/main/java/com/ttubeog/domain/auth/filter/JwtFilter.java b/src/main/java/com/ttubeog/domain/auth/filter/JwtFilter.java new file mode 100644 index 00000000..4a10a9b5 --- /dev/null +++ b/src/main/java/com/ttubeog/domain/auth/filter/JwtFilter.java @@ -0,0 +1,47 @@ +package com.ttubeog.domain.auth.filter; + +import com.ttubeog.domain.auth.application.JwtTokenService; +import com.ttubeog.domain.member.application.MemberService; +import com.ttubeog.domain.member.domain.Member; +import com.ttubeog.domain.member.dto.MemberDto; +import com.ttubeog.domain.member.dto.response.MemberDetailRes; +import com.ttubeog.global.config.security.token.MemberPrincipal; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.GenericFilterBean; + +import java.io.IOException; +import java.nio.file.attribute.UserPrincipal; + +@RequiredArgsConstructor +public class JwtFilter extends GenericFilterBean { + public static final String AUTHORIZATION_HEADER = "Authorization"; + private final JwtTokenService jwtTokenService; + private final MemberService memberService; + + // 액세스 토큰이 유효한지 확인하고 SecurityContext에 계정 정보를 저장 + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; + logger.info("[JwtFilter] : " + httpServletRequest.getRequestURL().toString()); + String jwt = resolveToken(httpServletRequest); + } + + // 헤더에서 액세스 토큰 가져오는 코드 + private String resolveToken(HttpServletRequest servletRequest) { + String bearerToken = servletRequest.getHeader(AUTHORIZATION_HEADER); + + if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) { + return bearerToken.substring(7); + } + + return null; + } +} From 57fb0e6f1145e4892ee71883fa33d87286f75a78 Mon Sep 17 00:00:00 2001 From: arinming Date: Fri, 19 Jan 2024 14:29:22 +0900 Subject: [PATCH 12/12] =?UTF-8?q?[FIX]=20=EB=B9=8C=EB=93=9C=20=EC=97=90?= =?UTF-8?q?=EB=9F=AC=20=ED=95=B4=EA=B2=B0=20(#1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build.gradle | 1 + .../CustomDefaultOAuth2UserService.java | 148 ++++++------- .../CustomMemberDetailsService.java | 6 +- .../CustomTokenProviderService.java | 14 +- ...yConfig.java => SecurityDomainConfig.java} | 4 +- .../ttubeog/domain/auth/filter/JwtFilter.java | 7 - .../member/application/MemberService.java | 6 +- .../ttubeog/domain/member/domain/Member.java | 13 +- .../domain/member/domain/Provider.java | 4 +- .../member/presentation/MemberController.java | 8 +- .../config/security/SecurityConfig.java | 198 +++++++++--------- .../config/security/auth/OAuth2UserInfo.java | 2 + .../security/auth/OAuth2UserInfoFactory.java | 58 ++--- .../config/security/auth/company/Kakao.java | 111 +++++----- .../{CurrentMember.java => CurrentUser.java} | 2 +- ...emberPrincipal.java => UserPrincipal.java} | 16 +- 16 files changed, 301 insertions(+), 297 deletions(-) rename src/main/java/com/ttubeog/domain/auth/config/{SecurityConfig.java => SecurityDomainConfig.java} (97%) rename src/main/java/com/ttubeog/global/config/security/token/{CurrentMember.java => CurrentUser.java} (89%) rename src/main/java/com/ttubeog/global/config/security/token/{MemberPrincipal.java => UserPrincipal.java} (80%) diff --git a/build.gradle b/build.gradle index 1f331e96..c241d2db 100644 --- a/build.gradle +++ b/build.gradle @@ -33,6 +33,7 @@ dependencies { annotationProcessor "org.springframework.boot:spring-boot-configuration-processor" runtimeOnly 'com.mysql:mysql-connector-j' + implementation 'org.mariadb.jdbc:mariadb-java-client:2.6.2' testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test' diff --git a/src/main/java/com/ttubeog/domain/auth/application/CustomDefaultOAuth2UserService.java b/src/main/java/com/ttubeog/domain/auth/application/CustomDefaultOAuth2UserService.java index 5e7d7577..d6891f08 100644 --- a/src/main/java/com/ttubeog/domain/auth/application/CustomDefaultOAuth2UserService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/CustomDefaultOAuth2UserService.java @@ -1,74 +1,74 @@ -package com.ttubeog.domain.auth.application; - -import com.ttubeog.domain.member.domain.Provider; -import com.ttubeog.domain.member.domain.Role; -import com.ttubeog.domain.member.domain.Member; -import com.ttubeog.domain.member.domain.repository.MemberRepository; -import com.ttubeog.global.DefaultAssert; -import com.ttubeog.global.config.security.auth.OAuth2UserInfo; -import com.ttubeog.global.config.security.auth.OAuth2UserInfoFactory; -import com.ttubeog.global.config.security.token.MemberPrincipal; -import lombok.RequiredArgsConstructor; -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; - -import java.util.Optional; - -@RequiredArgsConstructor -@Service -public class CustomDefaultOAuth2UserService extends DefaultOAuth2UserService{ - - private final MemberRepository memberRepository; - - @Override - public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2AuthenticationException { - OAuth2User oAuth2User = super.loadUser(oAuth2UserRequest); - try { - return processOAuth2User(oAuth2UserRequest, oAuth2User); - } catch (Exception e) { - DefaultAssert.isAuthentication(e.getMessage()); - } - return null; - } - - private OAuth2User processOAuth2User(OAuth2UserRequest oAuth2UserRequest, OAuth2User oAuth2User) { - OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(oAuth2UserRequest.getClientRegistration().getRegistrationId(), oAuth2User.getAttributes()); - DefaultAssert.isAuthentication(!oAuth2UserInfo.getEmail().isEmpty()); - - Optional userOptional = memberRepository.findByEmail(oAuth2UserInfo.getEmail()); - Member member; - if(userOptional.isPresent()) { - member = userOptional.get(); - DefaultAssert.isAuthentication(member.getProvider().equals(Provider.valueOf(oAuth2UserRequest.getClientRegistration().getRegistrationId()))); - member = updateExistingMember(member, oAuth2UserInfo); - } else { - member = registerNewMember(oAuth2UserRequest, oAuth2UserInfo); - } - - return MemberPrincipal.create(member, oAuth2User.getAttributes()); - } - - private Member registerNewMember(OAuth2UserRequest oAuth2UserRequest, OAuth2UserInfo oAuth2UserInfo) { - Member member = Member.builder() - .provider(Provider.valueOf(oAuth2UserRequest.getClientRegistration().getRegistrationId())) - .providerId(oAuth2UserInfo.getId()) - .name(oAuth2UserInfo.getName()) - .email(oAuth2UserInfo.getEmail()) - .imageUrl(oAuth2UserInfo.getImageUrl()) - .role(Role.USER) - .build(); - - return memberRepository.save(member); - } - - private Member updateExistingMember(Member member, OAuth2UserInfo oAuth2UserInfo) { - - member.updateName(oAuth2UserInfo.getName()); - member.updateImageUrl(oAuth2UserInfo.getImageUrl()); - - return memberRepository.save(member); - } -} +//package com.ttubeog.domain.auth.application; +// +//import com.ttubeog.domain.member.domain.Provider; +//import com.ttubeog.domain.member.domain.Role; +//import com.ttubeog.domain.member.domain.Member; +//import com.ttubeog.domain.member.domain.repository.MemberRepository; +//import com.ttubeog.global.DefaultAssert; +//import com.ttubeog.global.config.security.auth.OAuth2UserInfo; +//import com.ttubeog.global.config.security.token.UserPrincipal; +//import lombok.RequiredArgsConstructor; +//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; +// +//import java.util.Optional; +// +//@RequiredArgsConstructor +//@Service +//public class CustomDefaultOAuth2UserService extends DefaultOAuth2UserService { +// +// private final MemberRepository memberRepository; +// +// @Override +// public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2AuthenticationException { +// OAuth2User oAuth2User = super.loadUser(oAuth2UserRequest); +// try { +// return processOAuth2User(oAuth2UserRequest, oAuth2User); +// } catch (Exception e) { +// DefaultAssert.isAuthentication(e.getMessage()); +// } +// return null; +// } +// +// private OAuth2User processOAuth2User(OAuth2UserRequest oAuth2UserRequest, OAuth2User oAuth2User) { +// OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(oAuth2UserRequest.getClientRegistration().getRegistrationId(), oAuth2User.getAttributes()); +// DefaultAssert.isAuthentication(!oAuth2UserInfo.getEmail().isEmpty()); +// +// Optional userOptional = memberRepository.findByEmail(oAuth2UserInfo.getEmail()); +// Member member; +// if (userOptional.isPresent()) { +// member = userOptional.get(); +// DefaultAssert.isAuthentication(member.getProvider().equals(Provider.valueOf(oAuth2UserRequest.getClientRegistration().getRegistrationId()))); +// member = updateExistingMember(member, oAuth2UserInfo); +// } else { +// member = registerNewMember(oAuth2UserRequest, oAuth2UserInfo); +// } +// +// return UserPrincipal.create(member, oAuth2User.getAttributes()); +// } +// +// private Member registerNewMember(OAuth2UserRequest oAuth2UserRequest, OAuth2UserInfo oAuth2UserInfo) { +// Member member = Member.builder() +// .provider(Provider.valueOf(oAuth2UserRequest.getClientRegistration().getRegistrationId())) +// .providerId(oAuth2UserInfo.getId()) +// .name(oAuth2UserInfo.getName()) +// .email(oAuth2UserInfo.getEmail()) +// .imageUrl(oAuth2UserInfo.getImageUrl()) +// .refreshToken(oAuth2UserInfo.getRefreshToken()) +// .role(Role.USER) +// .build(); +// +// return memberRepository.save(member); +// } +// +// private Member updateExistingMember(Member member, OAuth2UserInfo oAuth2UserInfo) { +// +// member.updateName(oAuth2UserInfo.getName()); +// member.updateImageUrl(oAuth2UserInfo.getImageUrl()); +// +// return memberRepository.save(member); +// } +//} diff --git a/src/main/java/com/ttubeog/domain/auth/application/CustomMemberDetailsService.java b/src/main/java/com/ttubeog/domain/auth/application/CustomMemberDetailsService.java index a8b63c67..cb94a0c1 100644 --- a/src/main/java/com/ttubeog/domain/auth/application/CustomMemberDetailsService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/CustomMemberDetailsService.java @@ -3,7 +3,7 @@ import com.ttubeog.domain.member.domain.Member; import com.ttubeog.domain.member.domain.repository.MemberRepository; import com.ttubeog.global.DefaultAssert; -import com.ttubeog.global.config.security.token.MemberPrincipal; +import com.ttubeog.global.config.security.token.UserPrincipal; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import org.springframework.security.core.userdetails.UserDetails; @@ -27,7 +27,7 @@ public UserDetails loadUserByUsername(String email) throws UsernameNotFoundExcep new UsernameNotFoundException("멤버 정보를 찾을 수 없습니다.") ); - return MemberPrincipal.create(member); + return UserPrincipal.create(member); } @Transactional @@ -35,7 +35,7 @@ public UserDetails loadUserById(Long id) { Optional user = memberRepository.findById(id); DefaultAssert.isOptionalPresent(user); - return MemberPrincipal.create(user.get()); + return UserPrincipal.create(user.get()); } } diff --git a/src/main/java/com/ttubeog/domain/auth/application/CustomTokenProviderService.java b/src/main/java/com/ttubeog/domain/auth/application/CustomTokenProviderService.java index a6672c38..2b56e6c3 100644 --- a/src/main/java/com/ttubeog/domain/auth/application/CustomTokenProviderService.java +++ b/src/main/java/com/ttubeog/domain/auth/application/CustomTokenProviderService.java @@ -2,7 +2,7 @@ import com.ttubeog.domain.auth.dto.TokenMapping; import com.ttubeog.global.config.security.OAuth2Config; -import com.ttubeog.global.config.security.token.MemberPrincipal; +import com.ttubeog.global.config.security.token.UserPrincipal; import io.jsonwebtoken.*; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; @@ -27,7 +27,7 @@ public class CustomTokenProviderService { private CustomMemberDetailsService customMemberDetailsService; public TokenMapping refreshToken(Authentication authentication, String refreshToken) { - MemberPrincipal memberPrincipal = (MemberPrincipal) authentication.getPrincipal(); + UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal(); Date now = new Date(); Date accessTokenExpiresIn = new Date(now.getTime() + oAuth2Config.getAuth().getAccessTokenExpirationMsec()); @@ -37,21 +37,21 @@ public TokenMapping refreshToken(Authentication authentication, String refreshTo Key key = Keys.hmacShaKeyFor(keyBytes); String accessToken = Jwts.builder() - .setSubject(Long.toString(memberPrincipal.getId())) + .setSubject(Long.toString(userPrincipal.getId())) .setIssuedAt(new Date()) .setExpiration(accessTokenExpiresIn) .signWith(key, SignatureAlgorithm.HS512) .compact(); return TokenMapping.builder() - .userEmail(memberPrincipal.getEmail()) + .userEmail(userPrincipal.getEmail()) .accessToken(accessToken) .refreshToken(refreshToken) .build(); } public TokenMapping createToken(Authentication authentication) { - MemberPrincipal memberPrincipal = (MemberPrincipal) authentication.getPrincipal(); + UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal(); Date now = new Date(); @@ -64,7 +64,7 @@ public TokenMapping createToken(Authentication authentication) { Key key = Keys.hmacShaKeyFor(keyBytes); String accessToken = Jwts.builder() - .setSubject(Long.toString(memberPrincipal.getId())) + .setSubject(Long.toString(userPrincipal.getId())) .setIssuedAt(new Date()) .setExpiration(accessTokenExpiresIn) .signWith(key, SignatureAlgorithm.HS512) @@ -76,7 +76,7 @@ public TokenMapping createToken(Authentication authentication) { .compact(); return TokenMapping.builder() - .userEmail(memberPrincipal.getEmail()) + .userEmail(userPrincipal.getEmail()) .accessToken(accessToken) .refreshToken(refreshToken) .build(); diff --git a/src/main/java/com/ttubeog/domain/auth/config/SecurityConfig.java b/src/main/java/com/ttubeog/domain/auth/config/SecurityDomainConfig.java similarity index 97% rename from src/main/java/com/ttubeog/domain/auth/config/SecurityConfig.java rename to src/main/java/com/ttubeog/domain/auth/config/SecurityDomainConfig.java index 4e255c55..e4b60c46 100644 --- a/src/main/java/com/ttubeog/domain/auth/config/SecurityConfig.java +++ b/src/main/java/com/ttubeog/domain/auth/config/SecurityDomainConfig.java @@ -17,11 +17,11 @@ @RequiredArgsConstructor @Configuration -public class SecurityConfig { +public class SecurityDomainConfig { private final JwtTokenService jwtTokenService; private final MemberService memberService; - @Bean + @Bean(name = "domainAuth") public AuthenticationManager authenticationManager( final AuthenticationConfiguration authenticationConfiguration ) throws Exception { diff --git a/src/main/java/com/ttubeog/domain/auth/filter/JwtFilter.java b/src/main/java/com/ttubeog/domain/auth/filter/JwtFilter.java index 4a10a9b5..2b5fcaed 100644 --- a/src/main/java/com/ttubeog/domain/auth/filter/JwtFilter.java +++ b/src/main/java/com/ttubeog/domain/auth/filter/JwtFilter.java @@ -2,23 +2,16 @@ import com.ttubeog.domain.auth.application.JwtTokenService; import com.ttubeog.domain.member.application.MemberService; -import com.ttubeog.domain.member.domain.Member; -import com.ttubeog.domain.member.dto.MemberDto; -import com.ttubeog.domain.member.dto.response.MemberDetailRes; -import com.ttubeog.global.config.security.token.MemberPrincipal; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import lombok.RequiredArgsConstructor; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.userdetails.UserDetails; import org.springframework.util.StringUtils; import org.springframework.web.filter.GenericFilterBean; import java.io.IOException; -import java.nio.file.attribute.UserPrincipal; @RequiredArgsConstructor public class JwtFilter extends GenericFilterBean { diff --git a/src/main/java/com/ttubeog/domain/member/application/MemberService.java b/src/main/java/com/ttubeog/domain/member/application/MemberService.java index 4aa7d84c..baf6cee7 100644 --- a/src/main/java/com/ttubeog/domain/member/application/MemberService.java +++ b/src/main/java/com/ttubeog/domain/member/application/MemberService.java @@ -5,7 +5,7 @@ import com.ttubeog.domain.member.domain.Member; import com.ttubeog.domain.member.domain.repository.MemberRepository; import com.ttubeog.global.DefaultAssert; -import com.ttubeog.global.config.security.token.MemberPrincipal; +import com.ttubeog.global.config.security.token.UserPrincipal; import com.ttubeog.global.payload.ApiResponse; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; @@ -21,8 +21,8 @@ public class MemberService { private final MemberRepository memberRepository; // 현재 유저 조회 - public ResponseEntity getCurrentUser(MemberPrincipal memberPrincipal){ - Optional checkUser = memberRepository.findById(memberPrincipal.getId()); + public ResponseEntity getCurrentUser(UserPrincipal userPrincipal){ + Optional checkUser = memberRepository.findById(userPrincipal.getId()); DefaultAssert.isOptionalPresent(checkUser); Member member = checkUser.get(); diff --git a/src/main/java/com/ttubeog/domain/member/domain/Member.java b/src/main/java/com/ttubeog/domain/member/domain/Member.java index da6b439e..5f0cde49 100644 --- a/src/main/java/com/ttubeog/domain/member/domain/Member.java +++ b/src/main/java/com/ttubeog/domain/member/domain/Member.java @@ -13,7 +13,8 @@ @Getter public class Member extends BaseEntity { - @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @@ -34,9 +35,10 @@ public class Member extends BaseEntity { private String providerId; private String platform; + private String refreshToken; @Builder - public Member(Long id, String name, String email, String imageUrl, Boolean emailVerified, String password, Provider provider, Role role, String providerId, String platform) { + public Member(Long id, String name, String email, String imageUrl, String password, Provider provider, Role role, String providerId, String platform, String refreshToken) { this.id = id; this.name = name; this.email = email; @@ -46,13 +48,16 @@ public Member(Long id, String name, String email, String imageUrl, Boolean email this.role = role; this.providerId = providerId; this.platform = platform; + this.refreshToken = refreshToken; } - public void updateName(String name){ + + + public void updateName(String name) { this.name = name; } - public void updateImageUrl(String imageUrl){ + public void updateImageUrl(String imageUrl) { this.imageUrl = imageUrl; } } diff --git a/src/main/java/com/ttubeog/domain/member/domain/Provider.java b/src/main/java/com/ttubeog/domain/member/domain/Provider.java index 05baafc4..adf6227d 100644 --- a/src/main/java/com/ttubeog/domain/member/domain/Provider.java +++ b/src/main/java/com/ttubeog/domain/member/domain/Provider.java @@ -1,6 +1,6 @@ package com.ttubeog.domain.member.domain; public enum Provider { - kakao, - apple + KAKAO, + APPLE } diff --git a/src/main/java/com/ttubeog/domain/member/presentation/MemberController.java b/src/main/java/com/ttubeog/domain/member/presentation/MemberController.java index d31faba5..7470281d 100644 --- a/src/main/java/com/ttubeog/domain/member/presentation/MemberController.java +++ b/src/main/java/com/ttubeog/domain/member/presentation/MemberController.java @@ -2,8 +2,8 @@ import com.ttubeog.domain.member.application.MemberService; import com.ttubeog.domain.member.dto.response.MemberDetailRes; -import com.ttubeog.global.config.security.token.CurrentMember; -import com.ttubeog.global.config.security.token.MemberPrincipal; +import com.ttubeog.global.config.security.token.CurrentUser; +import com.ttubeog.global.config.security.token.UserPrincipal; import com.ttubeog.global.payload.ErrorResponse; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -33,9 +33,9 @@ public class MemberController { }) @GetMapping public ResponseEntity getCurrentMember( - @Parameter(description = "Accesstoken을 입력해주세요.", required = true) @CurrentMember MemberPrincipal memberPrincipal + @Parameter(description = "Accesstoken을 입력해주세요.", required = true) @CurrentUser UserPrincipal userPrincipal ) { - return memberService.getCurrentUser(memberPrincipal); + return memberService.getCurrentUser(userPrincipal); } } diff --git a/src/main/java/com/ttubeog/global/config/security/SecurityConfig.java b/src/main/java/com/ttubeog/global/config/security/SecurityConfig.java index a26ab307..f867fee3 100644 --- a/src/main/java/com/ttubeog/global/config/security/SecurityConfig.java +++ b/src/main/java/com/ttubeog/global/config/security/SecurityConfig.java @@ -1,99 +1,99 @@ -package com.ttubeog.global.config.security; - -import com.ttubeog.domain.auth.application.CustomDefaultOAuth2UserService; -import com.ttubeog.domain.auth.application.CustomMemberDetailsService; -import com.ttubeog.domain.auth.domain.repository.CustomAuthorizationRequestRepository; -import com.ttubeog.global.config.security.handler.CustomSimpleUrlAuthenticationFailureHandler; -import com.ttubeog.global.config.security.handler.CustomSimpleUrlAuthenticationSuccessHandler; -import com.ttubeog.global.config.security.token.CustomAuthenticationEntryPoint; -import com.ttubeog.global.config.security.token.CustomOncePerRequestFilter; -import lombok.RequiredArgsConstructor; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.dao.DaoAuthenticationProvider; -import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; -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.config.http.SessionCreationPolicy; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.web.SecurityFilterChain; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; - -import static org.springframework.security.config.Customizer.withDefaults; - - -@RequiredArgsConstructor -@Configuration -@EnableWebSecurity -public class SecurityConfig { - - private final CustomMemberDetailsService customMemberDetailsService; - private final CustomDefaultOAuth2UserService customOAuth2UserService; - private final CustomSimpleUrlAuthenticationSuccessHandler oAuth2AuthenticationSuccessHandler; - private final CustomSimpleUrlAuthenticationFailureHandler oAuth2AuthenticationFailureHandler; - private final CustomAuthorizationRequestRepository customAuthorizationRequestRepository; - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - - @Bean - public CustomOncePerRequestFilter customOncePerRequestFilter() { - return new CustomOncePerRequestFilter(); - } - - @Bean - public DaoAuthenticationProvider authenticationProvider() { - DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); - - authenticationProvider.setUserDetailsService(customMemberDetailsService); - authenticationProvider.setPasswordEncoder(passwordEncoder()); - - return authenticationProvider; - } - - @Bean - public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { - return authenticationConfiguration.getAuthenticationManager(); - } - - @Bean - public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http - .cors(withDefaults()) - .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) - .csrf(AbstractHttpConfigurer::disable) - .formLogin(AbstractHttpConfigurer::disable) - .httpBasic(AbstractHttpConfigurer::disable) - .exceptionHandling(exception -> exception.authenticationEntryPoint(new CustomAuthenticationEntryPoint())) - .authorizeHttpRequests(authorize -> authorize - .requestMatchers("/", "/error", "/favicon.ico", "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg", "/**/*.html", "/**/*.css", "/**/*.js") - .permitAll() - .requestMatchers("/swagger", "/swagger-ui.html", "/swagger-ui/**", "/api-docs", "/api-docs/**", "/v3/api-docs/**") - .permitAll() - .requestMatchers("/login/**","/auth/**", "/oauth2/**") - .permitAll() - .requestMatchers("/blog/**") - .permitAll() - .anyRequest() - .authenticated()) - .oauth2Login(oauth2 -> oauth2 - .authorizationEndpoint(authorization -> authorization - .baseUri("/oauth2/authorize") - .authorizationRequestRepository(customAuthorizationRequestRepository)) - .redirectionEndpoint(redirection -> redirection - .baseUri("/oauth2/callback/**")) - .userInfoEndpoint(userInfo -> userInfo - .userService(customOAuth2UserService)) - .successHandler(oAuth2AuthenticationSuccessHandler) - .failureHandler(oAuth2AuthenticationFailureHandler)); - - http.addFilterBefore(customOncePerRequestFilter(), UsernamePasswordAuthenticationFilter.class); - return http.build(); - } - -} +//package com.ttubeog.global.config.security; +// +//import com.ttubeog.domain.auth.application.CustomDefaultOAuth2UserService; +//import com.ttubeog.domain.auth.application.CustomMemberDetailsService; +//import com.ttubeog.domain.auth.domain.repository.CustomAuthorizationRequestRepository; +//import com.ttubeog.global.config.security.handler.CustomSimpleUrlAuthenticationFailureHandler; +//import com.ttubeog.global.config.security.handler.CustomSimpleUrlAuthenticationSuccessHandler; +//import com.ttubeog.global.config.security.token.CustomAuthenticationEntryPoint; +//import com.ttubeog.global.config.security.token.CustomOncePerRequestFilter; +//import lombok.RequiredArgsConstructor; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.security.authentication.AuthenticationManager; +//import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +//import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +//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.config.http.SessionCreationPolicy; +//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +//import org.springframework.security.crypto.password.PasswordEncoder; +//import org.springframework.security.web.SecurityFilterChain; +//import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +// +//import static org.springframework.security.config.Customizer.withDefaults; +// +// +//@RequiredArgsConstructor +//@Configuration +//@EnableWebSecurity +//public class SecurityConfig { +// +// private final CustomMemberDetailsService customMemberDetailsService; +// private final CustomDefaultOAuth2UserService customOAuth2UserService; +// private final CustomSimpleUrlAuthenticationSuccessHandler oAuth2AuthenticationSuccessHandler; +// private final CustomSimpleUrlAuthenticationFailureHandler oAuth2AuthenticationFailureHandler; +// private final CustomAuthorizationRequestRepository customAuthorizationRequestRepository; +// +// @Bean +// public PasswordEncoder passwordEncoder() { +// return new BCryptPasswordEncoder(); +// } +// +// @Bean +// public CustomOncePerRequestFilter customOncePerRequestFilter() { +// return new CustomOncePerRequestFilter(); +// } +// +// @Bean +// public DaoAuthenticationProvider authenticationProvider() { +// DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); +// +// authenticationProvider.setUserDetailsService(customMemberDetailsService); +// authenticationProvider.setPasswordEncoder(passwordEncoder()); +// +// return authenticationProvider; +// } +// +// @Bean +// public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { +// return authenticationConfiguration.getAuthenticationManager(); +// } +// +// @Bean +// public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { +// http +// .cors(withDefaults()) +// .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) +// .csrf(AbstractHttpConfigurer::disable) +// .formLogin(AbstractHttpConfigurer::disable) +// .httpBasic(AbstractHttpConfigurer::disable) +// .exceptionHandling(exception -> exception.authenticationEntryPoint(new CustomAuthenticationEntryPoint())) +// .authorizeHttpRequests(authorize -> authorize +// .requestMatchers("/", "/error", "/favicon.ico", "/**/*.png", "/**/*.gif", "/**/*.svg", "/**/*.jpg", "/**/*.html", "/**/*.css", "/**/*.js") +// .permitAll() +// .requestMatchers("/swagger", "/swagger-ui.html", "/swagger-ui/**", "/api-docs", "/api-docs/**", "/v3/api-docs/**") +// .permitAll() +// .requestMatchers("/login/**","/auth/**", "/oauth2/**") +// .permitAll() +// .requestMatchers("/blog/**") +// .permitAll() +// .anyRequest() +// .authenticated()) +// .oauth2Login(oauth2 -> oauth2 +// .authorizationEndpoint(authorization -> authorization +// .baseUri("/oauth2/authorize") +// .authorizationRequestRepository(customAuthorizationRequestRepository)) +// .redirectionEndpoint(redirection -> redirection +// .baseUri("/oauth2/callback/**")) +// .userInfoEndpoint(userInfo -> userInfo +// .userService(customOAuth2UserService)) +// .successHandler(oAuth2AuthenticationSuccessHandler) +// .failureHandler(oAuth2AuthenticationFailureHandler)); +// +// http.addFilterBefore(customOncePerRequestFilter(), UsernamePasswordAuthenticationFilter.class); +// return http.build(); +// } +// +//} diff --git a/src/main/java/com/ttubeog/global/config/security/auth/OAuth2UserInfo.java b/src/main/java/com/ttubeog/global/config/security/auth/OAuth2UserInfo.java index 519f343f..802bd9d1 100644 --- a/src/main/java/com/ttubeog/global/config/security/auth/OAuth2UserInfo.java +++ b/src/main/java/com/ttubeog/global/config/security/auth/OAuth2UserInfo.java @@ -22,4 +22,6 @@ public Map getAttributes() { public abstract String getEmail(); public abstract String getImageUrl(); + + public abstract String getRefreshToken(); } diff --git a/src/main/java/com/ttubeog/global/config/security/auth/OAuth2UserInfoFactory.java b/src/main/java/com/ttubeog/global/config/security/auth/OAuth2UserInfoFactory.java index 182ab801..d0190425 100644 --- a/src/main/java/com/ttubeog/global/config/security/auth/OAuth2UserInfoFactory.java +++ b/src/main/java/com/ttubeog/global/config/security/auth/OAuth2UserInfoFactory.java @@ -1,29 +1,29 @@ -package com.ttubeog.global.config.security.auth; - -import com.ttubeog.domain.member.domain.Provider; -import com.ttubeog.global.DefaultAssert; -import com.ttubeog.global.config.security.auth.company.Kakao; - -import java.util.Map; - -public class OAuth2UserInfoFactory { - public static OAuth2UserInfo getOAuth2UserInfo(String registrationId, Map attributes) { -// if(registrationId.equalsIgnoreCase(Provider.google.toString())) { -// return new Google(attributes); -// } else if (registrationId.equalsIgnoreCase(Provider.facebook.toString())) { -// return new Facebook(attributes); -// } else if (registrationId.equalsIgnoreCase(Provider.github.toString())) { -// return new Github(attributes); -// } else if (registrationId.equalsIgnoreCase(Provider.naver.toString())) { -// return new Naver(attributes); -// } else if ~~ - if (registrationId.equalsIgnoreCase(Provider.kakao.toString())) { - return new Kakao(attributes); - } else if (registrationId.equalsIgnoreCase(Provider.apple.toString())) { - DefaultAssert.isAuthentication("애플 로그인은 구현 예정입니다."); - } else { - DefaultAssert.isAuthentication("해당 oauth2 기능은 지원하지 않습니다."); - } - return null; - } -} +//package com.ttubeog.global.config.security.auth; +// +//import com.ttubeog.domain.member.domain.Provider; +//import com.ttubeog.global.DefaultAssert; +//import com.ttubeog.global.config.security.auth.company.Kakao; +// +//import java.util.Map; +// +//public class OAuth2UserInfoFactory { +// public static OAuth2UserInfo getOAuth2UserInfo(String registrationId, Map attributes) { +//// if(registrationId.equalsIgnoreCase(Provider.google.toString())) { +//// return new Google(attributes); +//// } else if (registrationId.equalsIgnoreCase(Provider.facebook.toString())) { +//// return new Facebook(attributes); +//// } else if (registrationId.equalsIgnoreCase(Provider.github.toString())) { +//// return new Github(attributes); +//// } else if (registrationId.equalsIgnoreCase(Provider.naver.toString())) { +//// return new Naver(attributes); +//// } else if ~~ +// if (registrationId.equalsIgnoreCase(Provider.kakao.toString())) { +// return new Kakao(attributes); +// } else if (registrationId.equalsIgnoreCase(Provider.apple.toString())) { +// DefaultAssert.isAuthentication("애플 로그인은 구현 예정입니다."); +// } else { +// DefaultAssert.isAuthentication("해당 oauth2 기능은 지원하지 않습니다."); +// } +// return null; +// } +//} diff --git a/src/main/java/com/ttubeog/global/config/security/auth/company/Kakao.java b/src/main/java/com/ttubeog/global/config/security/auth/company/Kakao.java index 21749067..ccf5f01b 100644 --- a/src/main/java/com/ttubeog/global/config/security/auth/company/Kakao.java +++ b/src/main/java/com/ttubeog/global/config/security/auth/company/Kakao.java @@ -1,54 +1,57 @@ -package com.ttubeog.global.config.security.auth.company; - -import com.ttubeog.domain.member.domain.Provider; -import com.ttubeog.global.config.security.auth.OAuth2UserInfo; - -import java.util.Map; - -public class Kakao extends OAuth2UserInfo { - - public Kakao(Map attributes) { - super(attributes); - } - - @Override - public String getId() { - return attributes.get("id").toString(); - } - - @Override - public String getName() { - Map properties = (Map) attributes.get("properties"); - - if (properties == null) { - return null; - } - - return (String) properties.get("nickname"); - } - - @Override - public String getEmail() { - Map properties = (Map) attributes.get("kakao_account"); - if (properties == null) { - return null; - } - return (String) properties.get("email"); - } - - @Override - public String getImageUrl() { - Map properties = (Map) attributes.get("properties"); - - if (properties == null) { - return null; - } - - return (String) properties.get("thumbnail_image"); - } - - @Override - public String getProvider(){ - return Provider.kakao.toString(); - } -} +//package com.ttubeog.global.config.security.auth.company; +// +//import com.ttubeog.domain.member.domain.Provider; +//import com.ttubeog.global.config.security.auth.OAuth2UserInfo; +// +//import java.util.Map; +// +//public class Kakao extends OAuth2UserInfo { +// +// public Kakao(Map attributes) { +// super(attributes); +// } +// +// @Override +// public String getId() { +// return attributes.get("id").toString(); +// } +// +// @Override +// public String getName() { +// Map properties = (Map) attributes.get("properties"); +// +// if (properties == null) { +// return null; +// } +// +// return (String) properties.get("nickname"); +// } +// +// @Override +// public String getEmail() { +// Map properties = (Map) attributes.get("kakao_account"); +// if (properties == null) { +// return null; +// } +// return (String) properties.get("email"); +// } +// +// @Override +// public String getImageUrl() { +// Map properties = (Map) attributes.get("properties"); +// +// if (properties == null) { +// return null; +// } +// +// return (String) properties.get("thumbnail_image"); +// } +// +// @Override +// public String getProvider(){ +// return Provider.kakao.toString(); +// } +// +// @Override +// public String getRefreshToken() { return} +//} diff --git a/src/main/java/com/ttubeog/global/config/security/token/CurrentMember.java b/src/main/java/com/ttubeog/global/config/security/token/CurrentUser.java similarity index 89% rename from src/main/java/com/ttubeog/global/config/security/token/CurrentMember.java rename to src/main/java/com/ttubeog/global/config/security/token/CurrentUser.java index ea1970da..5e48850c 100644 --- a/src/main/java/com/ttubeog/global/config/security/token/CurrentMember.java +++ b/src/main/java/com/ttubeog/global/config/security/token/CurrentUser.java @@ -8,6 +8,6 @@ @Retention(RetentionPolicy.RUNTIME) @Documented @AuthenticationPrincipal -public @interface CurrentMember { +public @interface CurrentUser { } diff --git a/src/main/java/com/ttubeog/global/config/security/token/MemberPrincipal.java b/src/main/java/com/ttubeog/global/config/security/token/UserPrincipal.java similarity index 80% rename from src/main/java/com/ttubeog/global/config/security/token/MemberPrincipal.java rename to src/main/java/com/ttubeog/global/config/security/token/UserPrincipal.java index e222aef5..afc6d046 100644 --- a/src/main/java/com/ttubeog/global/config/security/token/MemberPrincipal.java +++ b/src/main/java/com/ttubeog/global/config/security/token/UserPrincipal.java @@ -13,7 +13,7 @@ import java.util.Map; @Getter -public class MemberPrincipal implements OAuth2User, UserDetails{ +public class UserPrincipal implements OAuth2User, UserDetails{ private final Member member; @@ -23,7 +23,7 @@ public class MemberPrincipal implements OAuth2User, UserDetails{ private final Collection authorities; private Map attributes; - public MemberPrincipal(Member member, Long id, String email, String password, Collection authorities) { + public UserPrincipal(Member member, Long id, String email, String password, Collection authorities) { this.member = member; this.id = id; this.email = email; @@ -31,9 +31,9 @@ public MemberPrincipal(Member member, Long id, String email, String password, Co this.authorities = authorities; } - public static MemberPrincipal create(final Member member) { + public static UserPrincipal create(final Member member) { List authorities = Collections.singletonList(new SimpleGrantedAuthority(member.getRole().getValue())); - return new MemberPrincipal( + return new UserPrincipal( member, member.getId(), member.getEmail(), @@ -42,10 +42,10 @@ public static MemberPrincipal create(final Member member) { ); } - public static MemberPrincipal create(Member member, Map attributes) { - MemberPrincipal memberPrincipal = MemberPrincipal.create(member); - memberPrincipal.setAttributes(attributes); - return memberPrincipal; + public static UserPrincipal create(Member member, Map attributes) { + UserPrincipal userPrincipal = UserPrincipal.create(member); + userPrincipal.setAttributes(attributes); + return userPrincipal; } public void setAttributes(Map attributes) {