[Spring Security] 내부 아키텍처 흐름 이해

김민주·2024년 12월 16일

Spring Security

Spring Security란 Spring에서 제공하는 인증과 인가에 대한 처리를 위임하는 프레임워크


AuthenticationProvider

사용자의 인증을 처리하는 핵심 컴포넌트

  • 사용자가 로그인 시 입력한 인증 정보(username, password 등)를 검증
  • 인증 성공 시 Authentication 객체를 생성하여 Spring Security에 전달
  • AuthenticationManager는 여러 AuthenticationProvider를 관리하고 인증 요청을 적절한 프로바이저로 전달함

SessionRegistry

Spring Security에서 활성화된 세션을 관리

  • 현재 활성화된 세션 목록과 각 세션의 사용자 정보를 추적함
  • 중복 로그인 방지, 세션 만료 등을 구현할 때 활용 가능

SecurityContextHolder

Spring Security에서 현재 인증된 사용자의 정보를 저장하고 제공하는 클래스
= SecurityContext를 관리하는 객체

  • 인증에 성공하면, 스프링 시큐리티가 SecurityContextHolder에 현재 사용자의 Authentication객체 저장
    • SecurityContext(Authentication객체가 저장되는 보관소)를 통해 인증정보를 관리함.
    • SecurityContext는 ThreadLocal에 저장되어, 현재 요청에만 유효하도록 동작하며, 현재 스레드에 연관된 인증정보를 저장 및 조회함.
    • httpRequest가 완료되면 SecurityContextHolder를 초기화하여 메모리누수가 방지됨.
  • 인증 정보 조회 시 SecurityContextHolder 이용

Authentication

인증된 사용자 인증요청을 나타내는 객체

  • principal : 인증된 사용자의 고유 식별자(이름, 이메일 등)
  • credentials : 사용자 자격 증명
  • authorities: 권한 목록
  • authenticated : 인증성공여부


인증 요청 시 처리 흐름

  1. 로그인 요청 (httpRequest 수신)
  2. 인증토큰생성(ex. UsernamePasswordAuthenticationToken)
  3. 스프링 시큐리티 필터(ex. UsernamePasswordAuthenticationFilter)가 요청을 처리
  4. AuthenticationProvider가 사용자 자격증명을 확인하여 인증처리함
  5. UserDetailsService에 사용자정보 넘기기
  6. AuthenticaitonProvider에서 UserDetails객체 비교
  7. 인증 성공시 필터에서 Authentication 객체가 생성되고, SecurityContext에 저장됨.

인증 저장 및 가져오는 코드

// 인증 성공 후, SecurityContextHolder에 저장
SecurityContextHolder.getContext().setAuthentication(authentication);
// SecurityContext에서 Authentication 객체 가져오기
 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
profile
𝐃𝐨𝐧'𝐭 𝐛𝐞 𝐚 𝐩𝐫𝐨𝐜𝐫𝐚𝐬𝐭𝐢𝐧𝐚𝐭𝐨𝐫💫

0개의 댓글