오봉이와 함께하는 개발 블로그
스프링 MVC 2 - 스프링 인터셉터 인증 체크 본문
728x90
스프링 인터셉터 - 인증 체크
서블릿 필터에서 사용했던 인증 체크 기능을 스프링 인터셉터로 개발해보자.
LoginCheckInterceptor
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
log.info("인증 체크 인터셉터 실행 {}", requestURI);
HttpSession session = request.getSession();
if(session == null || session.getAttribute(SessionConst.LOGIN_MEMBER) == null) {
log.info("미인증 사용자 요청");
// 로그인으로 redirect
response.sendRedirect("/login?redirectURL=" + requestURI);
return false;
}
return true;
}
}
서블릿 필터와 비교해서 코드가 매우 간결하다.
인증이라는 것은 컨트롤러 호출 전에만 호출되면 되기 때문에 preHandle
만 구현하면 된다.
순서 주의, 세밀한 설정 가능
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogInterceptor())
.order(1)
.addPathPatterns("/**")
.excludePathPatterns("/css/**", "/*.ico", "/error");
registry.addInterceptor(new LoginCheckInterceptor())
.order(2)
.addPathPatterns("/**")
.excludePathPatterns("/", "/members/add", "/login", "/logout", "/css/**", "/*.ico", "/error");
}
// ..................
}
인터셉터를 적용하거나 하지 않을 부분은 addPathPatterns
와 excludePathPatterns
에 작성하면 된다.
기본적으로 모든 경로에 해당 인터셉터를 적용하되 (/**)
, 홈(/
), 회원가입(/members/add
), 로그인(/login
), 리소스 조회(/css/**
), 오류(/error
)와 같은 부분은 로그인 체크 인터셉터를 적용하지 않는다.
서블릿 필터와 비교해보면 매우 편리한 것을 알 수 있다.
정리
서블릿 필터와 스프링 인터셉터는 웹과 관련된 공통 관심사를 해결하기 위한 기술이다.
서블릿 필터와 비교해서 스프링 인터셉터가 개발자 입장에서 훨씬 편리하다는 것을 코드로 이해할 수 있다.
특별한 문제가 없다면 인터셉터를 사용하는 것이 좋다.
출처 : 인프런 김영한 지식공유자님 강의 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술
728x90
'BE > Spring' 카테고리의 다른 글
스프링 MVC 2 - 서블릿 예외 처리 시작 (0) | 2022.08.30 |
---|---|
스프링 MVC 2 - ArgumentResolver 활용 (0) | 2022.08.30 |
스프링 MVC 2 - 스프링 인터셉터 소개 (0) | 2022.08.29 |
스프링 MVC 2 - 서블릿 필터 인증 체크 (0) | 2022.08.29 |
스프링 MVC 2 - 서블릿 필터 요청 로그 (0) | 2022.08.29 |
Comments