콘텐츠로 이동

2022 09 30

2022-09-30

Spring Security 테스팅

  • 참고: https://tecoble.techcourse.co.kr/post/2020-09-30-spring-security-test/
  • 개요

    • Spring Security 테스트 하려면 인증 정보를 미리 주입해야 하는 경우 종종 발생
    • SecurityContext에 직접 Authentication 주입하는 방법도 있음
      @BeforeEach
      void setUp() {
          UserDetails user = createUserDetails();
      
          SecurityContext context = SecurityContextHolder.getContext();
          context.setAuthentication(new UsernamePasswordAuthenticationToken());
      }
      
    • Spring Security가 인증 정보를 관리하는 방법
      • 인증 정보를 담은 Authentication 객체
      • 해당 정보를 SecurityContext에 보관
      • 이 SecurityContext는 SecurityContextHolder에 있는 ThreadLocal에 저장
      • 결과적으로 같은 Thread 내에서는 SecurityContextHolder를 통해 인증정보에 접근할 수 있음
  • @WithMockUser
    • 미리 인증된 사용자를 만들어두지 않아도 간단하게 인증이 필요한 메서드 테스트 가능
    • userName, password, role을 어노테이션에서 설정해줄 수 있음
  • @WithAnonymousUser
    • 인증되지 않은 사용자를 테스트에서 사용할 때 필요한 어노테이션
  • @WithUserDetails
    • UserDetails를 구현한 CustomUser가 있고, 다음

쓰레드 관점에서 본 Spring MVC 요청과정

  • 참고: https://livenow14.tistory.com/59
  • MVC FLOW
    1. 클라이언트가 HTTP 요청을 보냄
    2. 서버측의 welcome 소켓이 요청을 듣고 있다가 클라이언트 요청오면 연결 소켓 생성
    3. WAS는 HTTP 메시지 파싱하여 웹서버에서만 필요한 정보면 정적 페이지 반환
    4. Request, Response 객체 만들어 Filter 객체에 던져줌
    5. Filter에 등록된 내용(변경/체크/인증/인가 등) 로직 수행
    6. WAS에서 HttpServletRequest, HttpServletResponse 객체로 변환, 이를 DispatcherServlet에 넘겨줌
    7. DispatcherServlet내의 HandlerMapping, HandlerAdapter 인터페이스 구현체 실행
    8. request의 내용 바탕으로 서비스 실행되고 서비스 결과 넘겨줌
  • 각 과정은 공유되는걸까?
    • TCP 연결 쓰레드가 Servlet 쓰레드의 부모 쓰레드로 설정됨(?)
    • 요청이 들어오면 ThreadPool에서 여유 쓰레드가 있는지 확인
      • 있다면 요청에 대한 쓰레드 할당해줌
        • 이 쓰레드가 Servlet을 실행
        • 요청 끝나면 쓰레드는 쓰레드 풀에 반환
    • 쓰레드가 미리 생성되어 있음으로, 쓰레드 생성/종료 비용이 절약, 응답 시간 빨라짐