본문 바로가기
💻 뚝딱뚝딱/팀내도서대여시스템(OBRS)

[개발일지#017] 로그인 인터셉터(Interceptor) 적용하기

by 뚜루리 2025. 2. 20.
728x90
320x100
로그인 기능이 구현되어 있지만 로그인에 따라 권한 분리가 잘되어 있지 않다. 인터셉터를 적용해서 권한 분리를 해보자!

[개발목표]

  • 인터셉터를 이용하여 로그인 권한 분리 구현

 


[구현화면]

  • 빌린책, 나의책, 내정보 클릭시, 로그인하지 않았다면 로그인 페이지로 이동.

 


[구현하기]

1. 인터셉터, 필터, 스프링 시큐리티 선택하기

📌 권한, 로그인에 관련된 기능들은 인터셉터, 필터, 스프링 시큐리티 등이 있어 어떤걸 선택할지 고민해야 함. 이 사이드 프로젝드의 경우, 특정 URL에 대해 로그인 여부를 체크하고 로그인 페이지로 리다이렉트하는 기능을 구현하는 비교적 간단한 방식이기 때문에 인터셉터를 사용하였음!

 

🚀 인터셉터, 필터, 스프링 시큐리티 비교

방법 장점 단점 적합한 경우
필터 (Filter) 모든 요청을 처리 가능, 서블릿 단계에서 작동 Spring MVC에서 특정 경로만 걸러내기가 어려움 요청의 전처리/후처리가 필요할 때
인터셉터 (HandlerInterceptor) Spring MVC의 컨트롤러 전에 실행, 특정 URL만 선택 가능 보안 관련 기능이 부족함 로그인 체크, 권한 검사
스프링 시큐리티 (Spring Security) 강력한 보안 기능, 역할(Role) 기반 권한 부여 설정이 복잡함, 기본 설정을 커스터마이징해야 함 로그인/권한 제어가 중요한 경우

 

 

🔧 2. LoginInterceptor (인터셉터) 생성

package seulgi.bookRentalSystem.web.login;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);

        // 세션이 없거나 로그인 정보가 없으면 로그인 페이지로 이동
        if (session == null || session.getAttribute(SessionConst.LOGIN_MEMBER) == null) {
            String requestURI = request.getRequestURI();
            response.sendRedirect("/login?redirectURL=" + requestURI); // 로그인 후 원래 페이지로 리다이렉트
            return false; // 컨트롤러 실행 막기
        }
        return true;
    }
}

 

  • 요청이 들어오기 전에 preHandle()이 실행되어 로그인 여부를 체크
  • 로그인 정보가 없으면 /member/checkPassword (로그인 페이지)로 리다이렉트

 

3. WebConfig.java (인터셉터 등록)

package seulgi.bookRentalSystem.web;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import seulgi.bookRentalSystem.web.login.LoginInterceptor;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .order(1)
                .addPathPatterns(
                        "/book/{bookId}/rent", // 책 대여 버튼 클릭 시 로그인 체크
                        "/book/{authorId}/booksByAuthorId", // 나의 책 페이지
                        "/book/{bookRentalId}/booksByBookRentalId" // 빌린 책 페이지
                )
                .excludePathPatterns(
                        "/book", // 모든 책 리스트는 비회원도 볼 수 있음
                        "/book/{bookId}", // 책 단건 조회는 비회원도 볼 수 있음
                        "/login", "/logout", "/findLoginInfo" // 로그인 관련 경로 제외
                );
    }
}

 

 

  • addPathPatterns() → 로그인이 필요한 URL 설정
  • excludePathPatterns() → 비회원도 접근 가능한 URL 제외

 

 

🔧 4. book.html (책 단건 조회)에서 로그인 체크 추가

📌 대여 버튼을 클릭하면 로그인 여부를 체크하고 로그인 페이지로 이동

<!-- 대여 버튼 -->
<button class="btn btn-primary" id="rentBookBtn">대여하기</button>

<script>
document.getElementById("rentBookBtn").addEventListener("click", function() {
    let isLoggedIn = /*[[${session.loginId != null}]]*/ false; // 세션 기반 로그인 체크
    if (!isLoggedIn) {
        alert("로그인이 필요한 서비스입니다.");
        window.location.href = "/member/checkPassword"; // 로그인 페이지로 이동
    } else {
        window.location.href = "/book/{bookId}/rent"; // 실제 대여 처리 URL
    }
});
</script>
 
  • isLoggedIn 값이 false면 경고 메시지 출력 후 로그인 페이지로 이동
728x90
320x100

뚜루리님의
글이 좋았다면 응원을 보내주세요!