Skip to content

Commit

Permalink
Merge pull request #203 from ITZipProject/feature/user-invalid-jwt-er…
Browse files Browse the repository at this point in the history
…ror-fix

🐛 오류 수정 - 올바르지 않은 토큰값 전송 시 서버 내부 에러가 반환되는 오류 수정
  • Loading branch information
rowing0328 authored Jan 7, 2025
2 parents c96b7bc + bfb6026 commit 33bc89b
Showing 1 changed file with 45 additions and 13 deletions.
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
package darkoverload.itzip.feature.jwt.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import darkoverload.itzip.feature.jwt.infrastructure.CustomUserDetails;
import darkoverload.itzip.feature.jwt.infrastructure.JwtAuthenticationToken;
import darkoverload.itzip.feature.jwt.util.JwtTokenizer;
import darkoverload.itzip.feature.user.entity.Authority;
import darkoverload.itzip.global.config.response.code.CommonExceptionCode;
import darkoverload.itzip.global.config.response.code.ResponseCode;
import darkoverload.itzip.global.config.response.exception.RestApiException;
import darkoverload.itzip.global.config.response.response.ExceptionResponse;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import io.jsonwebtoken.security.SignatureException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
Expand All @@ -23,7 +27,6 @@
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

Expand All @@ -34,6 +37,7 @@
@RequiredArgsConstructor
public class TokenAuthenticationFilter extends OncePerRequestFilter {
private final JwtTokenizer jwtTokenizer;
private final ObjectMapper objectMapper;

/**
* 필터 메서드
Expand All @@ -53,16 +57,21 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
if (StringUtils.hasText(accessToken)) {
try {
getAuthentication(accessToken); // 토큰을 사용하여 인증 설정
} catch (ExpiredJwtException e) {
throw new RestApiException(CommonExceptionCode.JWT_UNKNOWN_ERROR);
} catch (UnsupportedJwtException e) {
throw new RestApiException(CommonExceptionCode.JWT_UNSUPPORTED_ERROR);
} catch (MalformedJwtException e) {
throw new RestApiException(CommonExceptionCode.JWT_INVALID_ERROR);
} catch (IllegalArgumentException e) {
throw new RestApiException(CommonExceptionCode.JWT_UNKNOWN_ERROR);
} catch (Exception e) {
throw new RestApiException(CommonExceptionCode.JWT_INTERNAL_ERROR);
} catch (ExpiredJwtException | IllegalArgumentException e) { // 알 수 없는 토큰 오류
setErrorResponse(response, CommonExceptionCode.JWT_UNKNOWN_ERROR);
return;
} catch (UnsupportedJwtException e) { // 지원하지 않는 토큰 오류
setErrorResponse(response, CommonExceptionCode.JWT_UNSUPPORTED_ERROR);
return;
} catch (SignatureException | MalformedJwtException e) { // 유효하지 않은 토큰 오류
setErrorResponse(response, CommonExceptionCode.JWT_INVALID_ERROR);
return;
} catch (RestApiException e) { // 이 전에 예외가 발생한 경우
setErrorResponse(response, e.getExceptionCode());
return;
} catch (Exception e) { // 알 수 없는 오류
setErrorResponse(response, CommonExceptionCode.JWT_INTERNAL_ERROR);
return;
}
}
filterChain.doFilter(request, response); // 다음 필터로 요청을 전달
Expand All @@ -79,10 +88,33 @@ private void getAuthentication(String token) {
String nickname = claims.get("nickname", String.class); // 이름을 가져옴
Authority authority = Authority.valueOf(claims.get("authority", String.class)); // 사용자 권한을 가져옴

Collection<? extends GrantedAuthority> authorities = Collections.singletonList(authority);
List<GrantedAuthority> authorities = Collections.singletonList(authority);

CustomUserDetails userDetails = new CustomUserDetails(email, "", nickname, (List<GrantedAuthority>) authorities);
CustomUserDetails userDetails = new CustomUserDetails(email, "", nickname, authorities);
Authentication authentication = new JwtAuthenticationToken(authorities, userDetails, null); // 인증 객체 생성
SecurityContextHolder.getContext().setAuthentication(authentication); // SecurityContextHolder에 인증 객체 설정
}

/**
* 핉터 내 예외 발생 시 예외 응답 반환
* @param response 응답 객체
* @param code 응답 코드
* @throws IOException
*/
private void setErrorResponse(HttpServletResponse response, ResponseCode code) throws IOException {
// 401 인증실패 응답 설정
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");

// 응답 바디 작성
ExceptionResponse errorResponse = ExceptionResponse.builder()
.status(code.getHttpStatus().toString())
.code(code.name())
.data(code.getData())
.build();

String jsonResponse = objectMapper.writeValueAsString(errorResponse);

response.getWriter().write(jsonResponse);
}
}

0 comments on commit 33bc89b

Please sign in to comment.