반응형
Spring GenericFilter Bean의 예외 처리
(스프링 보안 없이) 토큰 기반 인증을 구현했습니다.GenericFilterBean에서는 토큰을 확인하고 청구합니다.
public class MyTokenFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws MyAuthException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (!"OPTIONS".equals(request.getMethod())) {
String authHeader = request.getHeader("Authorization");
if (authHeader == null || !authHeader.startsWith("Token ")) {
throw new MyAuthException("Authorization header needed"); // Should return custom http status response like 400
}
String token = authHeader.substring(6);
try {
claimToken(token);
} catch (Exception e) {
throw new MyAuthException("Invalid token."); // Should return custom http status response like 401
}
}
chain.doFilter(req, res);
}
}
그래서 이 필터 안에서는 괜찮아 보입니다.하지만 다른 http 법령으로 json으로 답변을 보내야 합니다.응답 엔티티를 사용할 수 있습니다.@ControllerAdvisory가 있는 예외 처리기입니다.그래서 컨트롤러의 예외를 처리할 수 있습니다.
@ControllerAdvice
public class MyPrettyExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(MyAuthException.class)
@ResponseBody
public ResponseEntity<Object> handleCustomException(HttpServletRequest req, MyAuthException ex) {
Map<String, String> responseBody = new HashMap<>();
responseBody.put("error", "true");
responseBody.put("message", ex.getMessage());
return new ResponseEntity<Object>(responseBody, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
필터와 컨트롤러의 예외(필터는 컨트롤러보다 먼저 작업하므로 컨트롤러와 동일한 범위가 아님)와 필터의 작동 방식을 알고 있습니다.그래서 당연히 컨트롤러 어드바이스로는 필터의 예외를 처리할 수 없습니다.
예를 들어 필터에서 예외를 처리하는 효율적인 방법은 무엇입니까?그것에 대한 다른 방법을 제게 제안해 주실 수 있습니까?
응답을 사용해야 합니다.보내기 오류 코드 및 상태에 대한 sendError:
public class MyTokenFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (!"OPTIONS".equals(request.getMethod())) {
String authHeader = request.getHeader("Authorization");
if (authHeader == null || !authHeader.startsWith("Token ")) {
//throw new MyAuthException("Authorization header needed"); // Should return custom http status response like 400
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Authorization header needed");
return ;
}
String token = authHeader.substring(6);
try {
claimToken(token);
} catch (Exception e) {
//throw new MyAuthException("Invalid token."); // Should return custom http status response like 401
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid token.");
return ;
}
}
chain.doFilter(req, res);
}
}
언급URL : https://stackoverflow.com/questions/31496256/exception-handling-in-spring-genericfilterbean
반응형
'programing' 카테고리의 다른 글
| C11의 최신 변경 사항 (0) | 2023.10.20 |
|---|---|
| Linux Bash to mysql: 외부 값이 있는 레코드 선택 또는 삭제 (0) | 2023.10.15 |
| 플랫폼 간 일관된 의사 난수 (0) | 2023.10.15 |
| jQuery애니메이션 스크롤 (0) | 2023.10.15 |
| 앱의 배경 이미지를 반복하는 방법 (0) | 2023.10.15 |