From a3d2acd271272994022373ddfb2ed876be626074 Mon Sep 17 00:00:00 2001 From: chanwoo7 Date: Wed, 4 Sep 2024 21:48:43 +0900 Subject: [PATCH] =?UTF-8?q?[refactor]=20#142=20JWT=20=EC=9D=B8=EC=A6=9D=20?= =?UTF-8?q?=ED=95=84=ED=84=B0=EB=A7=81=20=EB=A1=9C=EC=A7=81=20=EB=A6=AC?= =?UTF-8?q?=ED=8C=A9=ED=86=A0=EB=A7=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../global/JwtAuthenticationFilter.java | 99 +++++++++++-------- 1 file changed, 59 insertions(+), 40 deletions(-) diff --git a/src/main/java/com/book/backend/global/JwtAuthenticationFilter.java b/src/main/java/com/book/backend/global/JwtAuthenticationFilter.java index 0703750..710cb24 100644 --- a/src/main/java/com/book/backend/global/JwtAuthenticationFilter.java +++ b/src/main/java/com/book/backend/global/JwtAuthenticationFilter.java @@ -32,61 +32,80 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { log.trace("JwtAuthenticationFilter > doFilterInternal()"); - RequestWrapper wrappedRequest = new RequestWrapper(request); - String requestURI = wrappedRequest.getRequestURI(); // Swagger 경로에 대한 요청인 경우 필터링 과정 건너뛰기 - if (requestURI.startsWith("/swagger-ui/") || requestURI.startsWith("/v3/api-docs")) { + if (isSwaggerRequest(requestURI)) { filterChain.doFilter(wrappedRequest, response); return; } - // 요청 헤더에서 Authorization 요소 추출 + // 요청 헤더에서 Authorization 추출 String authorization = wrappedRequest.getHeader("Authorization"); - String username = "", token = ""; + if (authorization == null) { + setJwtException(request, ErrorCode.JWT_NOT_FOUND); + filterChain.doFilter(wrappedRequest, response); + return; + } + + processAuthorizationToken(authorization, wrappedRequest, response, filterChain); + } + + private boolean isSwaggerRequest(String requestURI) { + return requestURI.startsWith("/swagger-ui/") || requestURI.startsWith("/v3/api-docs"); + } + + private void processAuthorizationToken(String authorization, RequestWrapper wrappedRequest, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { try { - if (authorization != null && authorization.startsWith("Bearer ")) { // Bearer 토큰 파싱 - token = authorization.substring(7); // jwt token 파싱 - - // 블랙리스트에 있는 토큰인지 검증 - if (jwtUtil.isBlacklisted(token)) { - request.setAttribute("JWTException", new CustomException(ErrorCode.JWT_IS_BLACKLISTED)); - filterChain.doFilter(wrappedRequest, response); - return; - } - - username = jwtUtil.getUsernameFromToken(token); // username 가져옴 - - // 현재 SecurityContextHolder에 인증객체가 있는지 확인 - if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { - UserDetails userDetails; - userDetails = userDetailsService.loadUserByUsername(username); - - // 토큰 유효성 검증 - if (jwtUtil.isValidToken(token, userDetails)) { - UsernamePasswordAuthenticationToken authenticated - = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); - - authenticated.setDetails(new WebAuthenticationDetailsSource().buildDetails(wrappedRequest)); - SecurityContextHolder.getContext().setAuthentication(authenticated); - - // 토큰 갱신 - String newAccessToken = jwtUtil.generateToken(userDetails).getAccessToken(); - response.setHeader("Authorization", "Bearer " + newAccessToken); - } - } - } else { - request.setAttribute("JWTException", new CustomException(ErrorCode.JWT_NOT_FOUND)); + if (!authorization.startsWith("Bearer ")) { + throw new CustomException(ErrorCode.JWT_NOT_FOUND); + } + + String token = authorization.substring(7); + + // 블랙리스트에 있는 토큰인지 검증 + if (jwtUtil.isBlacklisted(token)) { + throw new CustomException(ErrorCode.JWT_IS_BLACKLISTED); + } + + String username = jwtUtil.getUsernameFromToken(token); + + // 현재 SecurityContextHolder에 인증객체가 있는지 확인 + if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { + authenticateUser(username, token, wrappedRequest, response); } } catch (ExpiredJwtException e) { - request.setAttribute("JWTException", new CustomException(ErrorCode.JWT_EXPIRED)); + setJwtException(wrappedRequest, ErrorCode.JWT_EXPIRED); + } catch (CustomException e) { + setJwtException(wrappedRequest, e.getCode()); } catch (Exception e) { - request.setAttribute("JWTException", new CustomException(ErrorCode.INVALID_CREDENTIALS)); + setJwtException(wrappedRequest, ErrorCode.INVALID_CREDENTIALS); + } finally { + filterChain.doFilter(wrappedRequest, response); + } + } + + private void authenticateUser(String username, String token, RequestWrapper request, HttpServletResponse response) throws IOException { + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + + // 토큰 유효성 검증 + if (!jwtUtil.isValidToken(token, userDetails)) { + return; } - filterChain.doFilter(wrappedRequest, response); + // SecurityContextHolder에 인증객체 추가 + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); + authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + SecurityContextHolder.getContext().setAuthentication(authentication); + + // 토큰 갱신 + String newAccessToken = jwtUtil.generateToken(userDetails).getAccessToken(); + response.setHeader("Authorization", "Bearer " + newAccessToken); + } + + private void setJwtException(HttpServletRequest request, ErrorCode errorCode) { + request.setAttribute("JWTException", new CustomException(errorCode)); } }