Skip to content

Commit

Permalink
Merge branch 'main' into #139-readme
Browse files Browse the repository at this point in the history
  • Loading branch information
chanwoo7 committed Sep 7, 2024
2 parents a0cf08b + 3a457c6 commit 41ee106
Showing 1 changed file with 59 additions and 40 deletions.
99 changes: 59 additions & 40 deletions src/main/java/com/book/backend/global/JwtAuthenticationFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}

0 comments on commit 41ee106

Please sign in to comment.