BackEnd/스프링 MVC

스프링 인터셉터 - 인증 체크

연향동큰손 2025. 1. 5. 16:34

로그인 처리를 쉽게 구현 할 수 있는 스프링 인터셉터에 대하여 공부 했다.

 

스프링 인터셉터는 스프링MVC가 제공하는 기술로 서블릿 필터를 이용하여 로그인을 구현 할때보다 쉽게 개발 가능하다.

 

 

< 스프링 인터셉터 흐름 >

HTTP 요청 -> WAS -> 필터 -> 서블릿 -> 스프링 인터셉터 -> 컨트롤러

 

 

스프링 인터셉터를 구현하기 위해서는 HandlerInterceptor를 구현 해주면 되는데, 총 3개의 메서드가 존재한다.

  1. preHandle  : 컨트롤러 호출 전에 호출된다.
  2. postHandle  : 컨트롤러 호출 후에 호출된다.
  3. afterCompletion : 뷰가 렌더링 된 이후에 호출된다.

 

 

로그인 처리 구현

 

package hello.login.web.interceptor;

import hello.login.web.SessionConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@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("미인증 사용자 요청");

            response.sendRedirect("/login?redirectURL="+requestURI); //로그인 화면으로 리다이렉트
            return false;
        }

        return true;
    }
}

 

위 코드를 이용해 컨트롤러 호출 전에 로그인 여부를 체크하여 인증된 사용자만 URL에 접속할 수 있도록 한다.

 

<WebConfig>

package hello.login.web;


import hello.login.web.filter.LogFilter;
import hello.login.web.filter.LoginCheckFilter;
import hello.login.web.interceptor.LogInterceptor;
import hello.login.web.interceptor.LoginCheckInterceptor;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;

@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("/","/member/add","/login","/logout","/css/**","/*.ico","/error");
    }
}

 

addPathPatterns, excludePathPatterns를 통해 인터셉터를 적용할 주소와 예외적으로 허용할 주소를 지정할 수 있다.

 

위 코드에서는 .addPathPatterns("/**")를 사용했기 때문에 모든 주소에 대해서 인터셉터를 적용한다.

 

단, .excludePathPatterns("/css/**", "/*.ico", "/error");에서 css관련주소나 아이콘, 에러와 관련된 주소는 허용했다.