|
10 | 10 | import lombok.RequiredArgsConstructor; |
11 | 11 | import org.dfbf.soundlink.global.exception.ErrorCode; |
12 | 12 | import org.dfbf.soundlink.global.exception.ResponseResult; |
| 13 | +import org.slf4j.Logger; |
| 14 | +import org.slf4j.LoggerFactory; |
13 | 15 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
14 | 16 | import org.springframework.security.core.context.SecurityContextHolder; |
| 17 | +import org.springframework.stereotype.Component; |
15 | 18 | import org.springframework.web.filter.OncePerRequestFilter; |
16 | 19 |
|
17 | 20 | import java.io.IOException; |
18 | 21 |
|
| 22 | +@Component |
19 | 23 | @RequiredArgsConstructor |
20 | 24 | public class JwtAuthenticationFilter extends OncePerRequestFilter { |
| 25 | + |
21 | 26 | private final JwtProvider jwtProvider; |
22 | 27 | private final ObjectMapper objectMapper = new ObjectMapper(); |
23 | 28 |
|
| 29 | + private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class); |
| 30 | + |
24 | 31 | @Override |
25 | 32 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) |
26 | 33 | throws ServletException, IOException { |
27 | | - String accessToken = jwtProvider.resolveAccessToken(request); //1.Access Token 추출 |
| 34 | + |
| 35 | + String accessToken = jwtProvider.resolveAccessToken(request); // 1. Access Token 추출 |
| 36 | + logger.info("Extracted Access Token: {}", accessToken); |
28 | 37 |
|
29 | 38 | try { |
30 | | - if(accessToken !=null && jwtProvider.validateToken(accessToken)) { //2.유효성 검사 |
31 | | - this.setAuthentication(accessToken); //3.유저정보 저장 |
32 | | - } |
33 | | - filterChain.doFilter(request, response); //필터 체인 진행(전달) |
| 39 | + if (accessToken != null && jwtProvider.validateToken(accessToken)) { // 2. 유효성 검사 |
| 40 | + logger.info("Valid JWT Token found, setting authentication."); |
| 41 | + setAuthentication(accessToken); // 3. 유저 정보 저장 |
| 42 | + } else { |
| 43 | + logger.warn("Invalid JWT Token or token is null"); |
| 44 | + } |
34 | 45 | } catch (ExpiredJwtException e) { |
35 | | - handleException(response, ErrorCode.TOKEN_EXPIRED); |
| 46 | + logger.error("Expired JWT Token: {}", e.getMessage(), e); // 토큰 만료 예외 처리 |
| 47 | + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); |
| 48 | + response.setContentType("application/json"); |
| 49 | + response.setCharacterEncoding("UTF-8"); |
| 50 | + response.getWriter().write(objectMapper.writeValueAsString(new ResponseResult(ErrorCode.TOKEN_EXPIRED))); |
| 51 | + return; |
36 | 52 | } catch (JwtException e) { |
37 | | - handleException(response, ErrorCode.TOKEN_INVALID); |
38 | | - }catch (Exception e) { |
39 | | - handleException(response, ErrorCode.INTERNAL_SERVER_ERROR); |
| 53 | + logger.error("Invalid JWT Token: {}", e.getMessage(), e); // 유효하지 않은 토큰 예외 처리 |
| 54 | + response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); |
| 55 | + response.setContentType("application/json"); |
| 56 | + response.setCharacterEncoding("UTF-8"); |
| 57 | + response.getWriter().write(objectMapper.writeValueAsString(new ResponseResult(ErrorCode.TOKEN_INVALID))); |
| 58 | + return; |
| 59 | + } catch (IllegalArgumentException e) { |
| 60 | + logger.error("Illegal Argument Exception: {}", e.getMessage(), e); // 잘못된 인자 예외 처리 |
| 61 | + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); |
| 62 | + response.setContentType("application/json"); |
| 63 | + response.setCharacterEncoding("UTF-8"); |
| 64 | + response.getWriter().write(objectMapper.writeValueAsString(new ResponseResult(ErrorCode.INTERNAL_SERVER_ERROR))); |
| 65 | + return; |
| 66 | + } catch (Exception e) { |
| 67 | + logger.error("Unexpected error during token validation: {}", e.getMessage(), e); // 예상치 못한 예외 처리 |
| 68 | + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "서버 오류가 발생했습니다."); |
| 69 | + return; |
40 | 70 | } |
41 | | - } |
42 | 71 |
|
| 72 | + logger.info("Proceeding with filter chain."); |
| 73 | + filterChain.doFilter(request, response); // 필터 체인 진행 |
| 74 | + } |
43 | 75 |
|
44 | | - //유저정보 저장 |
| 76 | + // 유저 정보 저장 |
45 | 77 | public void setAuthentication(String token) { |
46 | | - Long userId = jwtProvider.getUserId(token); //userId 추출 |
| 78 | + Long userId = jwtProvider.getUserId(token); // userId 추출 |
| 79 | + logger.info("Extracted userId from JWT: {}", userId); |
47 | 80 |
|
48 | 81 | if (userId == null) { |
| 82 | + logger.error("userId cannot be null"); |
49 | 83 | throw new IllegalArgumentException("userId cannot be null"); |
50 | 84 | } |
51 | 85 |
|
52 | 86 | CustomUserDetails userDetails = new CustomUserDetails(userId); |
| 87 | + logger.info("UserDetails created for userId: {}", userId); |
53 | 88 |
|
54 | | - // 인증토큰 생성 |
| 89 | + // 인증 토큰 생성 |
55 | 90 | UsernamePasswordAuthenticationToken authentication = |
56 | 91 | new UsernamePasswordAuthenticationToken(userId, null, userDetails.getAuthorities()); |
57 | 92 |
|
58 | | - // 인증정보 설정 |
| 93 | + // 인증 정보 설정 |
59 | 94 | SecurityContextHolder.getContext().setAuthentication(authentication); |
| 95 | + logger.info("Authentication set for userId: {}", userId); |
60 | 96 | } |
61 | | - |
62 | | - // 예외 발생 시 JSON 응답을 반환하는 메서드 |
63 | | - private void handleException(HttpServletResponse response, ErrorCode errorCode) throws IOException { |
64 | | - ResponseResult responseResult = new ResponseResult(errorCode); |
65 | | - |
66 | | - response.setStatus(errorCode.getStatus().value()); |
67 | | - response.setContentType("application/json"); |
68 | | - response.setCharacterEncoding("UTF-8"); |
69 | | - response.getWriter().write(objectMapper.writeValueAsString(responseResult)); |
70 | | - } |
71 | | - |
72 | 97 | } |
0 commit comments