From 2988ad7c19618b342968be1f7f213c4d40ad6b16 Mon Sep 17 00:00:00 2001 From: yunhacandy Date: Tue, 13 Aug 2024 16:18:12 +0900 Subject: [PATCH] =?UTF-8?q?refactor:=20Auth=20=EA=B4=80=EB=A0=A8=20?= =?UTF-8?q?=EC=BD=94=EB=93=9C=20=EB=A6=AC=ED=8C=A9=ED=86=A0=EB=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - MemberRole이 Member일때 서비스 이용 가능하게 SecurityConfig 코드 수정 - AuthService에서 RefreshTokenEntity 관련 코드 삽입 및 수정 --- .../growingpain/auth/service/AuthService.java | 54 +++++++++++++------ .../growingpain/config/SecurityConfig.java | 4 +- 2 files changed, 40 insertions(+), 18 deletions(-) diff --git a/src/main/java/cotato/growingpain/auth/service/AuthService.java b/src/main/java/cotato/growingpain/auth/service/AuthService.java index 794186e..b1b07fa 100644 --- a/src/main/java/cotato/growingpain/auth/service/AuthService.java +++ b/src/main/java/cotato/growingpain/auth/service/AuthService.java @@ -50,15 +50,19 @@ public Token createLoginInfo(LoginRequest request) { // 기존 회원이 존재하면 로그인 처리 Member member = existingMember.get(); if (!bCryptPasswordEncoder.matches(request.password(), member.getPassword())) { - throw new IllegalArgumentException("이메일 또는 비밀번호가 올바르지 않습니다."); + throw new AppException(ErrorCode.INVALID_PASSWORD); } - if (member.getMemberRole() == MemberRole.PENDING) { - return jwtTokenProvider.createToken(member.getId(), request.email(), MemberRole.PENDING.getDescription()); - } + String role = (member.getMemberRole() == MemberRole.PENDING) + ? MemberRole.PENDING.getDescription() + : MemberRole.MEMBER.getDescription(); + + Token token = jwtTokenProvider.createToken(member.getId(), member.getEmail(), role); - // 토큰 생성 및 반환 - return jwtTokenProvider.createToken(member.getId(), request.email(), MemberRole.MEMBER.getDescription()); + // RefreshTokenEntity 저장 또는 업데이트 + saveOrUpdateRefreshToken(member.getEmail(), token.getRefreshToken()); + + return token; } else { // 신규 회원일 경우 회원가입 처리 @@ -67,15 +71,19 @@ public Token createLoginInfo(LoginRequest request) { log.info("[회원 가입 서비스]: {}", request.email()); - Member newMember = Member.builder() + Member member = Member.builder() .password(bCryptPasswordEncoder.encode(request.password())) .email(request.email()) .memberRole(MemberRole.PENDING) .build(); - memberRepository.save(newMember); + memberRepository.save(member); // 회원가입 성공 후 토큰 생성 및 반환 - return jwtTokenProvider.createToken(newMember.getId(), request.email(),MemberRole.PENDING.getDescription()); + Token token = jwtTokenProvider.createToken(member.getId(), member.getEmail(), MemberRole.PENDING.getDescription()); + + saveOrUpdateRefreshToken(member.getEmail(), token.getRefreshToken()); + + return token; } } @@ -96,7 +104,12 @@ public Token completeSignup(CompleteSignupRequest request, String accessToken) { member.updateRole(MemberRole.MEMBER); memberRepository.save(member); - return jwtTokenProvider.createToken(member.getId(), member.getEmail(), MemberRole.MEMBER.getDescription()); + Token token = jwtTokenProvider.createToken(member.getId(), member.getEmail(), MemberRole.MEMBER.getDescription()); + + // RefreshTokenEntity 저장 + saveOrUpdateRefreshToken(member.getEmail(), token.getRefreshToken()); + + return token; } log.info("memberRole = {}", member.getMemberRole()); return null; @@ -127,25 +140,36 @@ public ReissueResponse tokenReissue(ReissueRequest request) { throw new AppException(ErrorCode.TOKEN_EXPIRED); } - if (!request.equals(request)) { + if (!findToken.getRefreshToken().equals(request.refreshToken())) { log.warn("[쿠키로 들어온 토큰과 DB의 토큰이 일치하지 않음.]"); throw new AppException(ErrorCode.REFRESH_TOKEN_NOT_EXIST); } Token token = jwtTokenProvider.createToken(memberId, email, role); - findToken.updateRefreshToken(token.getRefreshToken()); - refreshTokenRepository.save(findToken); log.info("재발급 된 액세스 토큰: {}", token.getAccessToken()); log.info("재발급 된 refresh 토큰: {}", token.getRefreshToken()); + + // RefreshTokenEntity 업데이트 + saveOrUpdateRefreshToken(email, token.getRefreshToken()); return ReissueResponse.from(token.getAccessToken(),token.getRefreshToken()); } + private void saveOrUpdateRefreshToken(String email, String refreshToken) { + RefreshTokenEntity refreshTokenEntity = refreshTokenRepository.findById(email) + .orElse(RefreshTokenEntity.builder().email(email).build()); + + refreshTokenEntity.updateRefreshToken(refreshToken); + refreshTokenRepository.save(refreshTokenEntity); + } + @Transactional public void logout(LogoutRequest request) { - String memberId = jwtTokenProvider.getEmail(request.refreshToken()); - RefreshTokenEntity existRefreshToken = refreshTokenRepository.findById(memberId) + String email = jwtTokenProvider.getEmail(request.refreshToken()); + + RefreshTokenEntity existRefreshToken = refreshTokenRepository.findById(email) .orElseThrow(() -> new AppException(ErrorCode.REFRESH_TOKEN_NOT_EXIST)); + setBlackList(request.refreshToken()); log.info("[로그아웃 된 리프레시 토큰 블랙리스트 처리]"); refreshTokenRepository.delete(existRefreshToken); diff --git a/src/main/java/cotato/growingpain/config/SecurityConfig.java b/src/main/java/cotato/growingpain/config/SecurityConfig.java index 750ce29..c37414a 100644 --- a/src/main/java/cotato/growingpain/config/SecurityConfig.java +++ b/src/main/java/cotato/growingpain/config/SecurityConfig.java @@ -7,7 +7,6 @@ import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; @@ -59,8 +58,7 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { UsernamePasswordAuthenticationFilter.class) .authorizeHttpRequests(request -> request .requestMatchers(WHITE_LIST).permitAll() - .requestMatchers(HttpMethod.GET, REQUIRED_AUTHENTICATE).authenticated() - .requestMatchers(HttpMethod.GET).permitAll() + .requestMatchers(REQUIRED_AUTHENTICATE).hasAuthority("ROLE_MEMBER") .anyRequest().authenticated() ); return http.build();