-
Notifications
You must be signed in to change notification settings - Fork 1
[Feature] SpringSecurity 및 소셜로그인 구현 #148
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
48 commits
Select commit
Hold shift + click to select a range
e2a2896
feat(auth): Spring Security 의존성 추가
Kimgyuilli ba50103
feat(auth): jwt, redis 의존성 추가
Kimgyuilli 52c79f3
feat(auth): auth, redis 프로필 추가
Kimgyuilli 61b61e1
feat(auth): user에 Social Provider 추가
Kimgyuilli ca2796d
feat(global): redis config 추가
Kimgyuilli 7c0a23a
feat(auth): auth 관련 repository 추가
Kimgyuilli 03e785d
feat(auth): auth 로직 구현
Kimgyuilli 4552201
feat(auth): 소셜 로그인 로직 구현
Kimgyuilli 5862fcf
feat(auth): apple 공개 키 캐싱 로직 추가
Kimgyuilli bae49fe
feat(auth): validateToken 반환 타입 불일치 수정
Kimgyuilli cc29146
docs(auth): javaDocs 작성
Kimgyuilli dadf4d6
feat(auth): 토큰 블랙리스트 로직 구현
Kimgyuilli 0276c7f
test(redis): 테스트용 redis mock 작성
Kimgyuilli 91f338d
test(security): security config 작성
Kimgyuilli a85415a
feat(auth): authorization filter test 분리
Kimgyuilli a192ecf
test(auth): userFixture auth 추가
Kimgyuilli 4910b2f
test(redis): bean 충동 해결
Kimgyuilli 0d86c12
faet(docker): 로컬용 redis docker-compose 설정 추가
Kimgyuilli 9e4be19
feat(swagger): swagger에 authorize 섹션 추가
Kimgyuilli 5c7dfb3
test: profile 중복 설정 정리
Kimgyuilli 12f2894
refactor(auth): jwt 토큰 생성 로직 통합
Kimgyuilli 2961840
refactor(auth): 예외 처리 로직 통합
Kimgyuilli 2267009
refactor(auth): AuthService 토큰 발급 메서드 추출
Kimgyuilli 9574baa
refactor(auth): 토큰 추출 로직 일원화 (Filter에서 Provider 사용)
Kimgyuilli 96854a9
refactor(auth): 에러 응답 유틸리티 생성
Kimgyuilli 3968b5f
refactor(redis): redis repository 탐색 경고 해결
Kimgyuilli 77959b9
Merge branch 'develop' into 145-feature/spring-security-jwt
Kimgyuilli 84e2775
feat(build.gradle): jjwt 버전 업데이트
Kimgyuilli b74e5c7
feat(.env.example): redis password 추가
Kimgyuilli f368d9c
feat(deploy): 배포 스크립트에 jjwt, redis 파라미터 추가
Kimgyuilli 4f536a8
feat(auth): Refresh Token 비교를 상수 시간 비교로 강화
Kimgyuilli 6c3d3c0
refactor(auth): Blacklist Repository HashSet Null-Safe하게 변경
Kimgyuilli 6162d1e
refactor(auth): TTL 검증 로직 통일
Kimgyuilli 5209481
fix(auth): 리프레시 토큰 인증 로직 개선
Kimgyuilli 36447c6
feat(auth): JwtProperties validation 검증 추가
Kimgyuilli f7444d0
feat(auth): 토큰 subject 파싱 실패 오류시 응답 통일
Kimgyuilli c996fa1
feat(auth): SceurityConfig 로그아웃 엔드포인트 보안 설정 불일치 문제 해결
Kimgyuilli f16e4e6
fix(auth): SecurityErrorResponseWriter 상태 코드/에러 코드 불일치 위험 제거 권장 문제 해결
Kimgyuilli 5127829
fix(auth): AuthController 공개 EndPoint swagger 명시
Kimgyuilli bd3e6f8
fix(auth): jwt default key value 정리
Kimgyuilli 11eb04d
fix(test): UserFixture id 원자성 보장 로직 추가
Kimgyuilli 8c6bcce
Merge branch '145-feature/spring-security-jwt' of https://github.com/…
Kimgyuilli 0a47728
feat(.env.example): 잘못된 문자 들어간거 수정
Kimgyuilli 14ca88a
feat(auth): 소셜 로그인 email unique 검증 정리
Kimgyuilli 5d87aec
feat(auth): jwt 키값 검증 로직 추가
Kimgyuilli c8855be
feat(auth): jwt 관련 예외처리 세분화
Kimgyuilli be2fb57
feat(env.example): jwt 값 예시 설명 추가
Kimgyuilli 8676eda
feat(User): social_provider, social_id 복합키 지정
Kimgyuilli File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
164 changes: 164 additions & 0 deletions
164
src/main/java/com/sopt/cherrish/domain/auth/application/service/AuthService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| package com.sopt.cherrish.domain.auth.application.service; | ||
|
|
||
| import java.nio.charset.StandardCharsets; | ||
| import java.security.MessageDigest; | ||
| import java.util.Optional; | ||
|
|
||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.transaction.annotation.Transactional; | ||
|
|
||
| import com.sopt.cherrish.domain.auth.domain.repository.AccessTokenBlacklistRepository; | ||
| import com.sopt.cherrish.domain.auth.domain.repository.RefreshTokenRepository; | ||
| import com.sopt.cherrish.domain.auth.exception.AuthErrorCode; | ||
| import com.sopt.cherrish.domain.auth.exception.AuthException; | ||
| import com.sopt.cherrish.domain.auth.infrastructure.jwt.JwtTokenProvider; | ||
| import com.sopt.cherrish.domain.auth.infrastructure.social.SocialUserInfo; | ||
| import com.sopt.cherrish.domain.auth.presentation.dto.request.SocialLoginRequestDto; | ||
| import com.sopt.cherrish.domain.auth.presentation.dto.request.TokenRefreshRequestDto; | ||
| import com.sopt.cherrish.domain.auth.presentation.dto.response.LoginResponseDto; | ||
| import com.sopt.cherrish.domain.auth.presentation.dto.response.TokenResponseDto; | ||
| import com.sopt.cherrish.domain.user.domain.model.User; | ||
| import com.sopt.cherrish.domain.user.domain.repository.UserRepository; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| /** | ||
| * 인증 관련 비즈니스 로직을 처리하는 서비스. | ||
| * | ||
| * <p>소셜 로그인, 토큰 재발급, 로그아웃 기능을 제공합니다.</p> | ||
| */ | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| @Transactional(readOnly = true) | ||
| public class AuthService { | ||
|
|
||
| private static final String DEFAULT_NAME = "사용자"; | ||
| private static final int DEFAULT_AGE = 0; | ||
|
|
||
| private final SocialLoginService socialLoginService; | ||
| private final UserRepository userRepository; | ||
| private final JwtTokenProvider jwtTokenProvider; | ||
| private final RefreshTokenRepository refreshTokenRepository; | ||
| private final AccessTokenBlacklistRepository accessTokenBlacklistRepository; | ||
|
|
||
| /** | ||
| * 소셜 로그인을 처리합니다. | ||
| * | ||
| * <p>소셜 토큰을 검증하고, 신규 사용자인 경우 회원가입을 진행합니다. | ||
| * 이후 Access Token과 Refresh Token을 발급합니다.</p> | ||
| * | ||
| * @param request 소셜 로그인 요청 (provider, token) | ||
| * @return 로그인 응답 (userId, isNewUser, accessToken, refreshToken) | ||
| * @throws AuthException 소셜 토큰이 유효하지 않은 경우 | ||
| */ | ||
| @Transactional | ||
| public LoginResponseDto login(SocialLoginRequestDto request) { | ||
| SocialUserInfo socialUserInfo = socialLoginService.authenticate( | ||
| request.provider(), | ||
| request.token() | ||
| ); | ||
|
|
||
| Optional<User> existingUser = userRepository.findBySocialProviderAndSocialId( | ||
| request.provider(), | ||
| socialUserInfo.socialId() | ||
| ); | ||
|
|
||
| boolean isNewUser = existingUser.isEmpty(); | ||
| User user; | ||
|
|
||
| if (isNewUser) { | ||
| user = User.builder() | ||
| .name(DEFAULT_NAME) | ||
| .age(DEFAULT_AGE) | ||
| .socialProvider(request.provider()) | ||
| .socialId(socialUserInfo.socialId()) | ||
| .email(socialUserInfo.email()) | ||
| .build(); | ||
| user = userRepository.save(user); | ||
Kimgyuilli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } else { | ||
| user = existingUser.get(); | ||
| } | ||
|
|
||
| TokenResponseDto tokens = issueTokenPair(user.getId()); | ||
|
|
||
| return new LoginResponseDto(user.getId(), isNewUser, tokens.accessToken(), tokens.refreshToken()); | ||
| } | ||
|
|
||
| /** | ||
| * Refresh Token으로 새로운 토큰 쌍을 발급합니다. | ||
| * | ||
| * <p>Refresh Token Rotation(RTR) 방식을 적용하여 재발급시 새로운 Refresh Token도 함께 발급합니다.</p> | ||
| * | ||
| * @param request 토큰 재발급 요청 (refreshToken) | ||
| * @return 새로운 Access Token과 Refresh Token | ||
| * @throws AuthException Refresh Token이 유효하지 않거나 만료된 경우 | ||
| */ | ||
| @Transactional | ||
| public TokenResponseDto refresh(TokenRefreshRequestDto request) { | ||
| String refreshToken = request.refreshToken(); | ||
|
|
||
| jwtTokenProvider.validateToken(refreshToken); | ||
|
|
||
| if (!jwtTokenProvider.isRefreshToken(refreshToken)) { | ||
| throw new AuthException(AuthErrorCode.INVALID_REFRESH_TOKEN); | ||
| } | ||
|
|
||
| Long userId = jwtTokenProvider.getUserId(refreshToken); | ||
|
|
||
| if (!userRepository.existsById(userId)) { | ||
| throw new AuthException(AuthErrorCode.USER_NOT_FOUND); | ||
| } | ||
|
|
||
| String storedToken = refreshTokenRepository.findByUserId(userId) | ||
| .orElseThrow(() -> new AuthException(AuthErrorCode.REFRESH_TOKEN_NOT_FOUND)); | ||
|
|
||
| if (!constantTimeEquals(storedToken, refreshToken)) { | ||
| throw new AuthException(AuthErrorCode.INVALID_REFRESH_TOKEN); | ||
| } | ||
Kimgyuilli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return issueTokenPair(userId); | ||
| } | ||
|
|
||
| /** | ||
| * 로그아웃을 처리합니다. | ||
| * | ||
| * <p>Redis에 저장된 Refresh Token을 삭제하고, Access Token을 블랙리스트에 추가하여 | ||
| * 해당 토큰들로 더 이상 인증이 불가능하게 합니다.</p> | ||
| * | ||
| * @param userId 로그아웃할 사용자 ID | ||
| * @param authorizationHeader Authorization 헤더 값 (Bearer 토큰) | ||
| */ | ||
| @Transactional | ||
| public void logout(Long userId, String authorizationHeader) { | ||
| refreshTokenRepository.deleteByUserId(userId); | ||
|
|
||
| String accessToken = jwtTokenProvider.extractToken(authorizationHeader); | ||
| if (accessToken != null) { | ||
| long remainingExpiration = jwtTokenProvider.getRemainingExpiration(accessToken); | ||
| accessTokenBlacklistRepository.add(accessToken, remainingExpiration); | ||
| } | ||
| } | ||
Kimgyuilli marked this conversation as resolved.
Show resolved
Hide resolved
Kimgyuilli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| private TokenResponseDto issueTokenPair(Long userId) { | ||
| String accessToken = jwtTokenProvider.createAccessToken(userId); | ||
| String refreshToken = jwtTokenProvider.createRefreshToken(userId); | ||
|
|
||
| refreshTokenRepository.save( | ||
| userId, | ||
| refreshToken, | ||
| jwtTokenProvider.getRefreshTokenExpiration() | ||
| ); | ||
|
|
||
| return new TokenResponseDto(accessToken, refreshToken); | ||
| } | ||
|
|
||
| private boolean constantTimeEquals(String a, String b) { | ||
| if (a == null || b == null) { | ||
| return false; | ||
| } | ||
| return MessageDigest.isEqual( | ||
| a.getBytes(StandardCharsets.UTF_8), | ||
| b.getBytes(StandardCharsets.UTF_8) | ||
| ); | ||
| } | ||
| } | ||
38 changes: 38 additions & 0 deletions
38
src/main/java/com/sopt/cherrish/domain/auth/application/service/SocialLoginService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| package com.sopt.cherrish.domain.auth.application.service; | ||
|
|
||
| import org.springframework.stereotype.Service; | ||
|
|
||
| import com.sopt.cherrish.domain.auth.domain.model.SocialProvider; | ||
| import com.sopt.cherrish.domain.auth.infrastructure.social.AppleAuthClient; | ||
| import com.sopt.cherrish.domain.auth.infrastructure.social.KakaoAuthClient; | ||
| import com.sopt.cherrish.domain.auth.infrastructure.social.SocialUserInfo; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| /** | ||
| * 소셜 로그인 인증을 처리하는 서비스. | ||
| * | ||
| * <p>소셜 플랫폼에 따라 적절한 인증 클라이언트를 선택하여 토큰을 검증합니다.</p> | ||
| */ | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class SocialLoginService { | ||
|
|
||
| private final KakaoAuthClient kakaoAuthClient; | ||
| private final AppleAuthClient appleAuthClient; | ||
|
|
||
| /** | ||
| * 소셜 토큰을 검증하고 사용자 정보를 반환합니다. | ||
| * | ||
| * @param provider 소셜 플랫폼 (KAKAO, APPLE) | ||
| * @param token 소셜 플랫폼에서 발급한 토큰 | ||
| * @return 소셜 사용자 정보 | ||
| * @throws com.sopt.cherrish.domain.auth.exception.AuthException 토큰이 유효하지 않은 경우 | ||
| */ | ||
| public SocialUserInfo authenticate(SocialProvider provider, String token) { | ||
| return switch (provider) { | ||
| case KAKAO -> kakaoAuthClient.getUserInfo(token); | ||
| case APPLE -> appleAuthClient.getUserInfo(token); | ||
| }; | ||
| } | ||
| } |
6 changes: 6 additions & 0 deletions
6
src/main/java/com/sopt/cherrish/domain/auth/domain/model/SocialProvider.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| package com.sopt.cherrish.domain.auth.domain.model; | ||
|
|
||
| public enum SocialProvider { | ||
| KAKAO, | ||
| APPLE | ||
| } |
50 changes: 50 additions & 0 deletions
50
.../java/com/sopt/cherrish/domain/auth/domain/repository/AccessTokenBlacklistRepository.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| package com.sopt.cherrish.domain.auth.domain.repository; | ||
|
|
||
| import java.util.concurrent.TimeUnit; | ||
|
|
||
| import org.springframework.data.redis.core.RedisTemplate; | ||
| import org.springframework.stereotype.Repository; | ||
|
|
||
| import lombok.RequiredArgsConstructor; | ||
|
|
||
| /** | ||
| * Access Token 블랙리스트를 Redis에 관리하는 저장소. | ||
| * | ||
| * <p>로그아웃된 Access Token을 저장하여 만료 전까지 재사용을 방지합니다. | ||
| * TTL은 토큰의 남은 만료 시간으로 설정되어 자동으로 정리됩니다.</p> | ||
| */ | ||
| @Repository | ||
| @RequiredArgsConstructor | ||
| public class AccessTokenBlacklistRepository { | ||
|
|
||
| private static final String KEY_PREFIX = "blacklist:"; | ||
|
|
||
| private final RedisTemplate<String, String> redisTemplate; | ||
|
|
||
| /** | ||
| * Access Token을 블랙리스트에 추가합니다. | ||
| * | ||
| * @param token 블랙리스트에 추가할 Access Token | ||
| * @param expirationMillis 토큰의 남은 만료 시간 (밀리초) | ||
| */ | ||
| public void add(String token, long expirationMillis) { | ||
| if (expirationMillis <= 0) { | ||
| return; | ||
| } | ||
| String key = KEY_PREFIX + token; | ||
| redisTemplate.opsForValue().set(key, "blacklisted", expirationMillis, TimeUnit.MILLISECONDS); | ||
| } | ||
|
|
||
| /** | ||
| * Access Token이 블랙리스트에 있는지 확인합니다. | ||
| * | ||
| * <p>Redis 연결 문제 등으로 null이 반환될 수 있으므로 null-safe 비교를 수행합니다.</p> | ||
| * | ||
| * @param token 확인할 Access Token | ||
| * @return 블랙리스트에 있으면 true, 없거나 확인 불가 시 false | ||
| */ | ||
| public boolean isBlacklisted(String token) { | ||
| String key = KEY_PREFIX + token; | ||
| return Boolean.TRUE.equals(redisTemplate.hasKey(key)); | ||
| } | ||
Kimgyuilli marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.