꾸물꾸물 졔의 개발공부

[Springboot] JWT(4)_ JWT 필터를 통해 토큰 만료시간 / 토큰 유효성 예외 발생시키기 본문

SPRING

[Springboot] JWT(4)_ JWT 필터를 통해 토큰 만료시간 / 토큰 유효성 예외 발생시키기

체제 2022. 8. 23. 23:29

이전포스팅 에서 JWT 필터를 적용시켜, 해당 토큰이 유효한지 검사하도록 하였다 .

토큰확인 과정에서 ,

  • 토큰의 유효기간이 지났거나 
  • 토큰의 형태가 아닌 값이라면 

예외를 발생시켜, 어딘가에서 잡아서 클라이언트에게 응답하도록 할 것이다 .

이번 포스팅에서는, 예외를 발생시켜서, 응답객체를 만들어 보았다.


try {
	//앞부분을 떼어내고 토큰값 추출, 인증정보얻어오기
    Authentication authentication = getAuthentication(request);
    // jwt 토큰으로 부터 획득한 인증 정보(authentication) 설정.
    SecurityContextHolder.getContext().setAuthentication(authentication);
 }catch(TokenExpiredException e){ 
  log.debug("filter-유효기간만료");
  request.setAttribute("exception", ErrorCode.EXPIRED_TOKEN.getErrorCode());
 }catch(Exception ex) {
  log.debug("filter-유효하지않은토큰");
  request.setAttribute("exception", ErrorCode.INVALID_TOKEN.getErrorCode());
}

▶ JwtAuthorizationFilter.java 에서, 토큰 검사하여 유효한 토큰이라면, 인증정보를 생성해 SecurityContextHolder 에 저장 

그렇지 않다면 , 핸들링한 예외를 catch 해주어서 AuthenticationEntryPoint로 날렸다. 

  • TokenExpiredException e : 토큰의 유효기간이 만료 예외
  • Exception e : 그 외의 토큰 예외 발생 ( 유효하지 않거나, 토큰 형식 아님 등등 ) 

   : request 에 이름을 "exception" 으로 하여, 해당하는 errorCode 로 값 전송 

 

 

 

 

 

ErrorCode.java - 토큰 예외 처리를 위한 error 상수 

public enum ErrorCode {

	EXPIRED_TOKEN("1001", "토큰 유효기간 만료. 재발급 요청하세요"),
	INVALID_TOKEN("1002", "옳지 않거나 틀린형식의 토큰입니다.");
	
	private String errorCode;
	private String errorMessage;
	
	public String getErrorMessage() {
		return errorMessage;
	}
	public String getErrorCode() {
		return errorCode;
	}
	
	ErrorCode(String errorCode, String errorMessage){
		this.errorCode = errorCode;
		this.errorMessage = errorMessage;
	}
}

: 각 예외 코드를 1001과 1002 로 하여 UnknownHttpStatusCodeException 예외가 발생하도록 유도하였다. 

 

 

 

 

CustomAuthenticationEntryPoint - 필터에서 발생한 예외를 받는 AuthenticationEntryPoint 구현 객체 

@Slf4j
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint{

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {
		String exception = (String)request.getAttribute("exception");
		ErrorCode errorCode;
		
		if(exception.equals(ErrorCode.EXPIRED_TOKEN.getErrorCode())) {
			errorCode = ErrorCode.EXPIRED_TOKEN;
			setResponse(response, errorCode);
			return;
		}if(exception.equals(ErrorCode.INVALID_TOKEN.getErrorCode())) {
			errorCode = ErrorCode.INVALID_TOKEN;
			setResponse(response,errorCode);
			return;
		}
	}
	private void setResponse(HttpServletResponse response, ErrorCode errorCode) 
	throws IOException{
		response.setContentType("application/json;charset=UTF-8");
		response.setStatus(Integer.parseInt(errorCode.getErrorCode()));
	}
	
}

▶request 에서 "exception" 을 불러와서, 

  •  유효기간 만료 토큰 ( ErrorCode.EXPIRED_TOKEN 이라면, 에러코드인 1001 로 응답 )  
  •  유효하지 않은 값의 토큰 ( ErrorCode.INVALID_TOKEN 이라면, 에러코드인 1002 로 응답 ) 

  → 해당 응답을 받는 곳에서는 UnknownHttpStatusCodeException 예외 발생 : 다음포스팅에서