스프링 시큐리티는 인증시 언제 세션에 저장할까?

seungho choi·2022년 7월 4일
1

로그인 구현도중 갑자기 막히는 부분이 생겼다. 아이디 + 패스워드 통해 인증을 하고 세션을 발급 해야하는데 살짝 감이 안잡혔다.
스프링 시큐리티에서 제공하는 AbstractAuthenticationProcessingFilter 를 상속 받아 인증을 구현해야하는건가? AbstractAuthenticationProcessingFilter를 이용해서 구현하기 보다는 스프링 MVC단에서 구현하고 싶은데 라는 생각을 했다.

하지만 궁금점이 생겼다. 스프링 MVC에서 인증 후 세션 처리를 어떻게 할까? 였다.

결과를 말하자면 동일한 쓰레드에 (SecurityContextHolder 기본 설정이 ThreadLocal이니까) SpringSecurityContextAuthentication 객체를 설정하면 자동적으로 스프링시큐리티가 세션에 저장해준다.

// controller나 service 든 상관없이 어느 로직에든
SecurityContextHolder
	.getContext()
    .setContext(Autehtncation);

어떻게 가능한걸까?

SecurityContextPersistenceFilter

SecurityContextPersistenceFilter는 기본 시큐리티 설정으로 했을 때 스프링 시큐리티 필터체인에 3번째로 등록 되어있는 필터이다.

얘 때문에 SecurityContextHolderSpringSecurityContext

이름만 들어도 어떠한 역할을 하는 필터인지 냄새가 난다.

공식문서를 한번 보고 코드를 까보자

얘의 역할은

  1. 필터가 실행되면 SecurityContextRepository 에서 저장된 SecurityContext 를 로드해 SecurityContextHolder에 설정(set) 한다.

    • SecurityContextRepository 구현체로는 기본적으로HttpSessionSecurityContextRepository 를 사용하기 때문에 세션에 있는 SecurityContext 를 로드한다.
  2. 그다음 doFilter 로 필터및 로직을 모두 수행한다음

  3. SecurityContextHolder 에서 SecurityContext를 조회한다음 SecurityContextRepository를 이용해서 SecurityContext 를 저장한다

    • 지금 이 로직 때문에 세션에 SecurityContext 저장되는 것이다.

Rerference

0개의 댓글