Skip to content

Commit f848cf1

Browse files
committed
[refactor] JWT 인증 에러 메시지 세분화
1 parent ca14d30 commit f848cf1

File tree

3 files changed

+30
-27
lines changed

3 files changed

+30
-27
lines changed

src/main/java/com/book/backend/domain/auth/service/JwtAuthenticationFilter.java

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -44,37 +44,40 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
4444
String authorization = wrappedRequest.getHeader("Authorization");
4545
String username = "", token = "";
4646

47-
if (authorization != null && authorization.startsWith("Bearer ")) { // Bearer 토큰 파싱
48-
token = authorization.substring(7); // jwt token 파싱
49-
try {
47+
try {
48+
if (authorization != null && authorization.startsWith("Bearer ")) { // Bearer 토큰 파싱
49+
token = authorization.substring(7); // jwt token 파싱
5050
username = jwtUtil.getUsernameFromToken(token); // username 가져옴
51-
} catch (ExpiredJwtException e) {
52-
filterChain.doFilter(wrappedRequest, response);
53-
return;
54-
}
5551

56-
// 현재 SecurityContextHolder에 인증객체가 있는지 확인
57-
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
58-
UserDetails userDetails;
59-
try {
60-
userDetails = userDetailsService.loadUserByUsername(username);
61-
} catch (CustomException e) {
62-
userDetails = userDetailsService.loadUserByKakaoId(username);
63-
}
52+
// 현재 SecurityContextHolder에 인증객체가 있는지 확인
53+
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
54+
UserDetails userDetails;
55+
try {
56+
userDetails = userDetailsService.loadUserByUsername(username);
57+
} catch (CustomException e) {
58+
userDetails = userDetailsService.loadUserByKakaoId(username);
59+
}
6460

65-
// 토큰 유효성 검증
66-
if (jwtUtil.isValidToken(token, userDetails)) {
67-
UsernamePasswordAuthenticationToken authenticated
68-
= new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
61+
// 토큰 유효성 검증
62+
if (jwtUtil.isValidToken(token, userDetails)) {
63+
UsernamePasswordAuthenticationToken authenticated
64+
= new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
6965

70-
authenticated.setDetails(new WebAuthenticationDetailsSource().buildDetails(wrappedRequest));
71-
SecurityContextHolder.getContext().setAuthentication(authenticated);
66+
authenticated.setDetails(new WebAuthenticationDetailsSource().buildDetails(wrappedRequest));
67+
SecurityContextHolder.getContext().setAuthentication(authenticated);
7268

73-
// 토큰 갱신
74-
String newAccessToken = jwtUtil.generateToken(userDetails).getAccessToken();
75-
response.setHeader("Authorization", "Bearer " + newAccessToken);
69+
// 토큰 갱신
70+
String newAccessToken = jwtUtil.generateToken(userDetails).getAccessToken();
71+
response.setHeader("Authorization", "Bearer " + newAccessToken);
72+
}
7673
}
74+
} else {
75+
request.setAttribute("JWTException", new CustomException(ErrorCode.JWT_NOT_FOUND));
7776
}
77+
} catch (ExpiredJwtException e) {
78+
request.setAttribute("JWTException", new CustomException(ErrorCode.JWT_EXPIRED));
79+
} catch (Exception e) {
80+
request.setAttribute("JWTException", new CustomException(ErrorCode.INVALID_CREDENTIALS));
7881
}
7982

8083
filterChain.doFilter(wrappedRequest, response);

src/main/java/com/book/backend/exception/ErrorCode.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ public enum ErrorCode {
2323

2424
INVALID_CREDENTIALS(HttpStatus.UNAUTHORIZED, "401", "사용자 인증에 실패했습니다."),
2525
LOGIN_REQUIRED(HttpStatus.UNAUTHORIZED, "401", "로그인이 필요합니다."),
26-
JWT_EXPIRED(HttpStatus.UNAUTHORIZED, "401", "JWT 토큰이 만료되었습니다. 다시 로그인해주세요."),
26+
JWT_NOT_FOUND(HttpStatus.UNAUTHORIZED, "401", "JWT 토큰이 입력되지 않았습니다."),
27+
JWT_EXPIRED(HttpStatus.UNAUTHORIZED, "401", "JWT 토큰이 만료되었습니다."),
2728
USER_NOT_FOUND(HttpStatus.NOT_FOUND, "404", "해당하는 사용자를 찾을 수 없습니다."),
2829
LOGIN_ID_DUPLICATED(HttpStatus.CONFLICT,"409", "사용자의 아이디가 중복됩니다."),
2930
BAD_REQUEST(HttpStatus.BAD_REQUEST, "400", "요청이 잘못되었습니다."),

src/main/java/com/book/backend/global/CustomAuthenticationEntryPoint.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package com.book.backend.global;
22

33
import com.book.backend.exception.CustomException;
4-
import com.book.backend.exception.ErrorCode;
54
import jakarta.servlet.ServletException;
65
import jakarta.servlet.http.HttpServletRequest;
76
import jakarta.servlet.http.HttpServletResponse;
@@ -13,7 +12,7 @@
1312
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
1413
@Override
1514
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
16-
CustomException customException = new CustomException(ErrorCode.LOGIN_REQUIRED);
15+
CustomException customException = (CustomException) request.getAttribute("JWTException");
1716
response.setStatus(customException.getCode().getStatus().value());
1817
response.setContentType("application/json");
1918
response.setCharacterEncoding("UTF-8");

0 commit comments

Comments
 (0)