Skip to content

Commit

Permalink
fix: Security 설정, JWT 필터 이전 설정 적용 (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
kyeong-hyeok committed Aug 5, 2023
1 parent 0588366 commit d884fec
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 10 deletions.
5 changes: 2 additions & 3 deletions src/main/java/com/project/mapdagu/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,8 @@ public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospe
.requestMatchers(mvcMatcherBuilder.pattern("/images/**")).permitAll()
.requestMatchers(mvcMatcherBuilder.pattern("/index.html")).permitAll()
.anyRequest().authenticated())
.oauth2Login(oauth2Login -> oauth2Login
// successHandler(oAuth2LoginSuccessHandler)
// .failureHandler(oAuth2LoginFailureHandler)
.oauth2Login(oauth2Login -> oauth2Login.successHandler(oAuth2LoginSuccessHandler)
.failureHandler(oAuth2LoginFailureHandler)
.userInfoEndpoint(userInfoEndPoint -> userInfoEndPoint.userService(customOauth2UserService)))
.addFilterAfter(customJsonUsernamePasswordAuthenticationFilter(), LogoutFilter.class)
.addFilterBefore(jwtAuthenticationProcessingFilter(), CustomJsonAuthenticationFilter.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ public class OAuth2LoginFailureHandler implements AuthenticationFailureHandler {
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws ServletException, IOException {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().write("소셜 로그인 실패! 서버 로그를 확인해주세요.");
log.info("소셜 로그인에 실패했습니다. 에러 메시지 : {}", exception.getMessage());
log.info("소셜 로그인에 실패했습니다. 에러 메시지 : {}", exception.fillInStackTrace());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,29 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
}

log.info("JwtAuthenticationProcessingFilter 호출");
String accessToken = jwtService.extractAccessToken(request).orElse(null);
// 사용자 요청 헤더에서 RefreshToken 추출-> RefreshToken이 없거나 유효하지 않다면 null
String refreshToken = jwtService.extractRefreshToken(request)
.filter(jwtService::isTokenValid)
.orElse(null);

// 리프레시 토큰이 요청 헤더에 존재하고 유효하다면, AccessToken이 만료된 것 -> AccessToken 재발급
if (refreshToken != null) {
String email = jwtService.extractEmail(refreshToken).orElseThrow(() -> new TokenException(ErrorCode.INVALID_TOKEN));
if (isRefreshTokenMatch(email, refreshToken)) {
String newAccessToken = jwtService.createAccessToken(email);
String newRefreshToken = jwtService.createRefreshToken(email);
jwtService.updateRefreshToken(email, newRefreshToken);
jwtService.sendAccessAndRefreshToken(response, newAccessToken, refreshToken);
}
return;
}

if (jwtService.isTokenValid(accessToken)) {
jwtService.extractEmail(accessToken)
.ifPresent(email -> memberRepository.findByEmail(email)
.ifPresent(this::saveAuthentication));
// AccessToken을 검사하고 인증 처리
// AccessToken이 없거나 유효하지 않다면, 인증 객체가 담기지 않은 상태로 다음 필터로 넘어가기 때문에 403 에러 발생
// AccessToken이 유효하다면, 인증 객체가 담긴 상태로 다음 필터로 넘어가기 때문에 인증 성공
else {
checkAccessTokenAndAuthentication(request, response, filterChain);
}
filterChain.doFilter(request, response);
}

public boolean isRefreshTokenMatch(String email, String refreshToken) {
Expand Down

0 comments on commit d884fec

Please sign in to comment.