현재 AccessToken, RefreshToken을 전부 쿠키로 담아서 전송하도록 만들었다.
심심해서 쿠키에 있는 AccessToken을 조금 바꿔서 swagger로 전송을 보냈더니 바로
SignatureException을 뱉어내기 시작했다.
문제는 내 코드에 해당 에러를 처리해주는 부분이 없었다는 거.
그래서 응답으로 이렇게 500에러가 터져버린다.
그래서 토큰에서 값을 파싱할 때 해당 예외처리를 진행해주었다.
public Long getUserId(String token){
try {
return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token)
.getBody().get("userId", Long.class);
} catch (ExpiredJwtException e) {
// 만료된 JWT에서도 userId는 가져옴.
return e.getClaims().get("userId", Long.class);
} catch (SignatureException e){
throw e;
}
}
마지막에 SignatureException을 던져주고
해당 메서드를 부르는 밖에서 catch로 잡아서 응답을 따로 생성해주었다.
catch (SignatureException e){
log.error("잘못된 JWT 서명입니다.", e);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 401 상태 코드 설정
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("{\n" +
" \"status\": \"error\",\n" +
" \"data\": null,\n" +
" \"message\": \"잘못된 서명의 토큰입니다.\"\n" +
"}");
return; // 필터 체인 처리 중지
}
토큰이 조작된 경우 응답을 잘 내뱉는 것을 확인할 수 있다.
심심함이 만든 예외처리였다.
반응형
'프로젝트 > 씈크럼 프로젝트' 카테고리의 다른 글
QueryDSL 도입기 (0) | 2024.02.17 |
---|---|
쿼리 메서드 사용으로 인한 성능 개선 (0) | 2024.02.09 |
Swagger를 배포한 상태로 사용해보기 (0) | 2024.02.01 |
현재 스프링부트 프로젝트에 유효성 검사 진행하기 (1) | 2024.01.31 |