본문 바로가기
코드잇 스프린트 : 프론트엔드 단기심화 5기 (백엔드 협업)

[Youtube] Spring boot 3.0 - Secure your API with JWT Token 해석 및 프로젝트 적용 기록(2)

by 아임제니퍼 2025. 1. 28.
필터에는 여러 가지 옵션이 있지만 여기 스키마에서 볼 수 있듯이 요청을 받을 때마다 
이 필터가 활성화되기를 원합니다.

따라서 사용자가 요청을 보낼 때마다 필터가 꺼지고
원하는 작업을 모두 수행할 수 있기 때문에
이 필터는 요청 필터당 한 번씩 호출되는 클래스를 확장해야 합니다.

public class JwtAuthenticationFilter extends OncePerRequestFilter {
}

 

이름에서 알 수 있듯이 각 요청마다 하나씩 필터가 될 것이므로
데이터 소스를 다운로드하고 여기에서 요청당 한 번씩 확인할 수 있습니다.


public abstract class OncePerRequestFilter extends GenericFilterBean {
}

 

public abstract class GenericFilterBean implements Filter, BeanNameAware, EnvironmentAware, EnvironmentCapable, ServletContextAware, InitializingBean, DisposableBean {
}

 

2가지 옵션
1. 요청 필터마다 한 번씩 이 필터를 사용
2. 필터 인터페이스를 구현

 

동일하지만 Spring에서 이미 제공된 것을 사용하겠습니다.
따라서 요청 필터마다 하나씩 사용하는 것이 낫습니다.

이제 메서드를 구현해보겠습니다.

	@Override
	protected void doFilterInternal(
		@NonNull HttpServletRequest request,
		@NonNull HttpServletResponse response,
		@NonNull FilterChain filterChain
	) throws ServletException, IOException {
    }

 

여기서 우리는 내부 필터링 및 do라는 메서드가 있으며, 
응답을 요청할 수 있는 세 가지 매개변수가 있고
필터 체인의 각 부분을 설명해드리겠습니다.

request는 우리의 request이며, response는 우리의 response이기도 합니다.
그래서 우리는 모든 request를 가로채서 사용할 수 있습니다.
예를 들어, request에서 데이터를 생성하고 추출할 수 있고,
response 내에서 새로운 데이터를 제공할 수 있습니다.

예를 들어, 제가 response에 header를 추가하고 싶다면,
이 필터를 사용하면 됩니다.
필터 체인은 책임 체인 디자인 패턴 입니다.

 

필터 체인


Spring Security's Servlet support is based on Servlet Filters, so it is helpful to look at the role of Filters generally first. The following image shows the typical layering of the handlers for a single HTTP request.

 

Figure 1. FilterChain

 

The client sends a request to the application, and the container creates a FilterChain, which contains the Filter instances and Servlet that should process the HttpServeltRequest, based on the path of the request URI. In a Spring MVC application, the Servlet is an instance of DispatcherServlet.

 

Spring을 왜 사용하나요?
유연함, 확장성
Spring Framework의 특징
OCP (Open for extension, Closed for modification)
Spring Framework
Spring JDBC
Spring MVC
Spring AOP
Srping ORM
What is Spring Web MVC?
Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very begining

 

Spring MVC

Front controller = Dispatcher Servlet

 

서블릿 (Servlet)
자바 어플리케이션에서 클라이언트의 요청을 처리하고 응답을 반환하는 역할을 하는 오브젝트
DipatcherServlet이란?
Dispatch(보내다/파견하다) + Servlet(웹 요청과 응답을 처리하는 객체)

 

DispatcherServlet의 역할
1. 클라이언트의 요청을 받아서 공통적인 작업 수행
2. 컨트롤러로 세부 작업을 위임
3. 클라이언트에게 보낼 뷰를 선택해서 최종 결과 생성

 

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
	// do something before the rest of the application
    chain.doFilter(request, response); // invoke the rest of the application
    // do something after the rest of the application
}
고정된 메서드 파라미터에서 값을 바인딩 해야 한다.

 

실제로 프로젝트에 적용한 코드
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

	private final JwtService jwtService;
	private final UserDetailsService userDetailsService;

        @Override
            protected void doFilterInternal(
                @NonNull HttpServletRequest request,
                @NonNull HttpServletResponse response,
                @NonNull FilterChain filterChain
            ) throws ServletException, IOException {
                if (request.getServletPath().contains("/auth")) {
                    filterChain.doFilter(request, response);
                    return;
                }

 

 

 

이 세 가지 매개변수가 null이 되서는 안되기 때문에 non-null 주석을 추가합니다.
이렇게 하면 더 이상 경고가 없고 이제 다음 단계로 넘어가기 전에 마지막으로 해야 할 일이 있습니다.
 마지막으로 해야 할 일은 이 class를 관리하고 싶다고 been에게 말하는 것입니다.

@service, @component, @repository 중 세 개가 동일한 주석이기 때문에 모두 작동하지만
@component로 만들겠습니다.

이제 필터를 사용할 준비가 되었습니다. 
이제 부분적으로 구현을 시작하겠습니다.

 

 

 

<참고>

https://docs.spring.io/spring-security/reference/servlet/architecture.html

[10분 테코톡] 안나의 스프링 MVC와 DispatcherServlet
https://youtu.be/hDKoMxhiKSM?si=QBz39prhdLbKoJqV


JWT 인증 필터를 왜 @Component로 등록하면 안 되는가?
https://xoals6536.tistory.com/entry/JWT-%EC%9D%B8%EC%A6%9D-%ED%95%84%ED%84%B0%EB%A5%BC-%EC%99%9C-Component%EB%A1%9C-%EB%93%B1%EB%A1%9D%ED%95%98%EB%A9%B4-%EC%95%88-%EB%90%98%EB%8A%94%EA%B0%80