-
Notifications
You must be signed in to change notification settings - Fork 1
MOSU-3 feat: OAuth2 로그인 기능 구현 #22
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
19 commits
Select commit
Hold shift + click to select a range
e4120f9
MOSU-3 feat: security.yml 추가
wlgns12370 5ae7b40
MOSU-3 feat: redis 설정 추가
wlgns12370 b6a4ebf
MOSU-3 fix: User id 타입 및 Role 변경
wlgns12370 efecd59
MOSU-3 feat: OAuth User Domain 구현
wlgns12370 45d61a8
MOSU-3 feat: Token 구현
wlgns12370 1cb452b
MOSU-3 feat: OAuth main 기능 구현
wlgns12370 0930c92
MOSU-3 feat: OAuth 설정 구현
wlgns12370 cb5dae9
MOSU-3 feat: TokenResponse 구현
wlgns12370 1f7ab21
MOSU-3 feat: RefreshToken 구현
wlgns12370 d6aa4c4
MOSU-3 feat: PrincipalDetails 구현
wlgns12370 4987967
MOSU-3 fix: 주석 제거 및 yml 파일명 변경
wlgns12370 51491dc
MOSU-3 fix: docker Redis 제거
wlgns12370 3137b54
MOSU-3 fix: TokenExceptionFilter 생성자 주입
wlgns12370 88f6a0d
MOSU-3 fix: 메서드 순서 조정
wlgns12370 48e04c3
MOSU-3 feat: Redis 연결 yml
wlgns12370 27b9201
MOSU-3 fix: final 제거
wlgns12370 14a035c
MOSU-3 fix: private static final 및 private 메서드 분리
wlgns12370 981d300
MOSU-3 feat: Kakao OAuth NPE 처리
wlgns12370 b3d7a55
MOSU-3 feat: OAuthProvider 구현
wlgns12370 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
19 changes: 19 additions & 0 deletions
19
src/main/java/life/mosu/mosuserver/applicaiton/auth/AccessTokenService.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,19 @@ | ||
| package life.mosu.mosuserver.applicaiton.auth; | ||
|
|
||
| import life.mosu.mosuserver.domain.user.UserJpaRepository; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| @Service | ||
| public class AccessTokenService extends JwtTokenService { | ||
|
|
||
| @Autowired | ||
| public AccessTokenService( | ||
| @Value("${jwt.access-token.expire-time}") final Long expireTime, | ||
| @Value("${jwt.secret}") final String secretKey, | ||
| final UserJpaRepository userRepositoy | ||
| ) { | ||
| super(expireTime, secretKey, "Access", "Authorization", userRepositoy); | ||
| } | ||
| } |
37 changes: 37 additions & 0 deletions
37
src/main/java/life/mosu/mosuserver/applicaiton/auth/AuthTokenManager.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,37 @@ | ||
| package life.mosu.mosuserver.applicaiton.auth; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import life.mosu.mosuserver.domain.user.UserJpaEntity; | ||
| import life.mosu.mosuserver.presentation.auth.dto.Token; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class AuthTokenManager { | ||
|
|
||
| private final AccessTokenService accessTokenService; | ||
| private final RefreshTokenService refreshTokenService; | ||
|
|
||
| public Token generateAuthToken(final UserJpaEntity user) { | ||
| final String accessToken = accessTokenService.generateJwtToken(user); | ||
| final String refreshToken = refreshTokenService.generateJwtToken(user); | ||
|
|
||
| refreshTokenService.cacheRefreshToken(user.getId(), refreshToken); | ||
|
|
||
| return Token.of(JwtTokenService.BEARER_TYPE, accessToken, refreshToken); | ||
| } | ||
|
|
||
| public Token reissueAccessToken(final HttpServletRequest servletRequest) { | ||
| final String refreshTokenString = refreshTokenService.resolveToken(servletRequest); | ||
|
|
||
| final Authentication authentication = refreshTokenService.getAuthentication(refreshTokenString); | ||
| final PrincipalDetails principalDetails = (PrincipalDetails) authentication.getPrincipal(); | ||
| final UserJpaEntity user = principalDetails.user(); | ||
|
|
||
| refreshTokenService.deleteRefreshToken(user.getId()); | ||
|
|
||
| return generateAuthToken(user); | ||
| } | ||
| } |
146 changes: 146 additions & 0 deletions
146
src/main/java/life/mosu/mosuserver/applicaiton/auth/JwtTokenService.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,146 @@ | ||
| package life.mosu.mosuserver.applicaiton.auth; | ||
|
|
||
| import io.jsonwebtoken.*; | ||
| import io.jsonwebtoken.io.Decoders; | ||
| import io.jsonwebtoken.security.Keys; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import life.mosu.mosuserver.domain.user.OAuthUserJpaEntity; | ||
| import life.mosu.mosuserver.domain.user.UserJpaEntity; | ||
| import life.mosu.mosuserver.domain.user.UserJpaRepository; | ||
| import life.mosu.mosuserver.global.exception.CustomRuntimeException; | ||
| import life.mosu.mosuserver.global.exception.ErrorCode; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; | ||
| import org.springframework.security.core.Authentication; | ||
|
|
||
| import java.security.Key; | ||
| import java.util.Date; | ||
|
|
||
| @Slf4j | ||
| public abstract class JwtTokenService { | ||
|
|
||
| protected static final String TOKEN_TYPE_KEY = "type"; | ||
| protected static final String BEARER_TYPE = "Bearer"; | ||
|
|
||
| protected final Long expireTime; | ||
| protected final Key key; | ||
| protected final String tokenType; | ||
| protected final String header; | ||
| protected final UserJpaRepository userRepository; | ||
|
|
||
| protected JwtTokenService( | ||
| final Long expireTime, | ||
| final String secretKey, | ||
| final String tokenType, | ||
| final String header, | ||
| final UserJpaRepository userJpaRepository | ||
| ) { | ||
| this.expireTime = expireTime; | ||
| this.key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey)); | ||
| this.tokenType = tokenType; | ||
| this.header = header; | ||
| this.userRepository = userJpaRepository; | ||
| } | ||
|
|
||
| /** | ||
| * JWT 토큰을 생성한다. | ||
| * | ||
| * @param user 토큰을 생성할 회원 | ||
| * @return 생성된 토큰 | ||
| */ | ||
| public String generateJwtToken(final UserJpaEntity user) { | ||
| final long now = System.currentTimeMillis(); | ||
| final Date expireTime = new Date(now + this.expireTime); | ||
|
|
||
| return Jwts.builder() | ||
| .setSubject(user.getLoginId()) | ||
| .claim(TOKEN_TYPE_KEY, tokenType) | ||
| .setExpiration(expireTime) | ||
| .signWith(key, SignatureAlgorithm.HS256) | ||
| .compact(); | ||
| } | ||
|
|
||
| /** | ||
| * JWT 토큰을 생성한다. | ||
| * | ||
| * @param user 토큰을 생성할 회원 | ||
| * @return 생성된 토큰 | ||
| */ | ||
| public String generateAccessToken(final OAuthUserJpaEntity user) { | ||
| final long now = System.currentTimeMillis(); | ||
| final Date expireTime = new Date(now + this.expireTime); | ||
|
|
||
| return Jwts.builder() | ||
| .setSubject(user.getEmail()) | ||
| .claim(TOKEN_TYPE_KEY, tokenType) | ||
| .setExpiration(expireTime) | ||
| .signWith(key, SignatureAlgorithm.HS256) | ||
| .compact(); | ||
| } | ||
|
|
||
| /** | ||
| * JWT 토큰을 파싱하여 Authentication 객체를 생성한다. | ||
| * | ||
| * @param token 토큰 | ||
| * @return 생성된 Authentication | ||
| */ | ||
| public Authentication getAuthentication(final String token) { | ||
| final Claims claims = validateAndParseToken(token); | ||
| final String loginId = claims.getSubject(); | ||
| final UserJpaEntity user = userRepository.findByLoginId(loginId) | ||
| .orElseThrow(() -> new IllegalArgumentException("존재하지 않는 사용자입니다.")); | ||
| final PrincipalDetails principalDetails = new PrincipalDetails(user); | ||
|
|
||
| return new UsernamePasswordAuthenticationToken(principalDetails, "", principalDetails.getAuthorities()); | ||
| } | ||
|
|
||
| private Claims parseClaims(String token) { | ||
| try { | ||
| return Jwts.parserBuilder() | ||
| .setSigningKey(key) | ||
| .build() | ||
| .parseClaimsJws(token) | ||
| .getBody(); | ||
| } catch (ExpiredJwtException exception) { | ||
| return exception.getClaims(); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * 토큰 검증과 함께 파싱을 수행한다. | ||
| * | ||
| * @param token 토큰 | ||
| * @return 파싱된 Claims | ||
| */ | ||
| protected Claims validateAndParseToken(final String token) { | ||
| try { | ||
| final Claims claims = parseClaims(token); | ||
|
|
||
| if (!claims.get(TOKEN_TYPE_KEY).equals(tokenType)) { | ||
| throw new CustomRuntimeException(ErrorCode.INVALID_TOKEN_TYPE); | ||
| } | ||
|
|
||
| if (claims.getExpiration().toInstant().isBefore(new Date().toInstant())) { | ||
| throw new CustomRuntimeException(ErrorCode.EXPIRED_TOKEN); | ||
| } | ||
| return claims; | ||
| } catch (JwtException | IllegalArgumentException exception) { | ||
| throw new CustomRuntimeException(ErrorCode.INVALID_TOKEN_TYPE); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * HttpServletRequest에서 토큰을 추출한다. 토큰이 없는 경우 null을 반환한다. | ||
| * | ||
| * @param request HttpServletRequest | ||
| * @return 추출된 토큰 | ||
| */ | ||
| public String resolveToken(final HttpServletRequest request) { | ||
| final String header = request.getHeader(this.header); | ||
|
|
||
| if (header != null && header.startsWith(BEARER_TYPE)) { | ||
| return header.replace(BEARER_TYPE, "").trim(); | ||
| } | ||
| return null; | ||
| } | ||
| } | ||
51 changes: 51 additions & 0 deletions
51
src/main/java/life/mosu/mosuserver/applicaiton/auth/PrincipalDetails.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,51 @@ | ||
| package life.mosu.mosuserver.applicaiton.auth; | ||
|
|
||
| import life.mosu.mosuserver.domain.user.UserJpaEntity; | ||
| import lombok.Getter; | ||
| import org.springframework.security.core.GrantedAuthority; | ||
| import org.springframework.security.core.authority.SimpleGrantedAuthority; | ||
| import org.springframework.security.core.userdetails.UserDetails; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.Collection; | ||
| import java.util.List; | ||
|
|
||
| public record PrincipalDetails(@Getter UserJpaEntity user) implements UserDetails { | ||
|
|
||
| @Override | ||
| public Collection<? extends GrantedAuthority> getAuthorities() { | ||
| List<GrantedAuthority> authorities = new ArrayList<>(); | ||
| authorities.add(new SimpleGrantedAuthority(user.getUserRole().name())); | ||
| return authorities; | ||
| } | ||
|
|
||
| @Override | ||
| public String getPassword() { | ||
| return user.getPassword(); | ||
| } | ||
|
|
||
| @Override | ||
| public String getUsername() { | ||
| return user.getLoginId(); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean isAccountNonExpired() { | ||
| return UserDetails.super.isAccountNonExpired(); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean isAccountNonLocked() { | ||
| return UserDetails.super.isAccountNonLocked(); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean isCredentialsNonExpired() { | ||
| return UserDetails.super.isCredentialsNonExpired(); | ||
| } | ||
|
|
||
| @Override | ||
| public boolean isEnabled() { | ||
| return UserDetails.super.isEnabled(); | ||
| } | ||
| } |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이 부분을 하나의 메소드로 접근하는데 인자라인으로 초기화 되는 경우를 구분하여 반복코드를 줄일 수 있을거 같아요!
JwtToken이라는 클래스 네이밍에서 AccessToken의 형태가 들어가면, 현재 구체적으로 분리되어있는 형식에서 좋지 않을 수도 있어요!
라고 공통 인터페이스를 만들어서
User와 OAuthUser 에 implements 하고, 해당 부분에서 넘겨주는 형태로 구성하고 인자는 JwtSubject 이걸로 받으면 어떨까라는 생각이 들어요!