스프링 Security

심규원·2024년 8월 29일

Spring Security 프레임워크는 Spring 서버에 필요한 인증 및 인가를 위해 많은 기능을 제공해 줌으로써 개발의 수고를 덜어줌.
Spring 프레임워크가 웹 서버 구현에 편의를 제공해주는것과 같다.

🔥 CSRF란?
  • CSRF(사이트 간 요청 위조, Cross-site request forgery)
    - 공격자가 인증된 브라우저에 저장된 쿠키의 세션 정보를 활용하여 웹 서버에 사용자가 의도하지 않은 요청을 전달하는 것입니다.
    - CSRF 설정이 되어있는 경우 html 에서 CSRF 토큰 값을 넘겨주어야 요청을 수신 가능합니다.
    - 쿠키 기반의 취약점을 이용한 공격 이기 때문에 REST 방식의 API 에서는 disable 가능합니다.
    - POST 요청마다 처리해 주는 대신 CSRF protection 을 disable 하겠습니다.
    - http.csrf((csrf) -> csrf.disable());

Spring Security - Filter Chain
스프링에서 모든 호출은 DispatcherServlet 을 통과하게 되고 이후에 각 요청을 담당하는 Controller 로 분배된다.

이 때, 각 요청에 대해서 공통적으로 처리해야할 필요가 있을 때 DispatcherServlet 이전에 단게가 필요하며 이것이 Filter 입니다.

스프링 시큐리티도 인증 및 인가를 처리하기 위해 Filter 를 사용하는데 스프링 시큐리티는 FilterChainProxy 를 통해서 상세 로직을 구현함

FormLogin 기반은 인증

Form Login 기반 인증은 인증이 필요한 URL 요청이 들어왔을 떄 인증이 되지 않았다면 로그인 페이지를 반환하는 형태

UsernamePasswordAuthenticationFilter

UsernamePasswordAuthenticationFilter는 Spring Security의 필터인 AbstractAuthenticationProcessingFilter를 상속한 Filter

기본적으로 Form Login 기반을 사용할 때 username 과 password 확인하여 인증

  • 인증 과정
    1. 사용자가 username과 password를 제출하면 UsernamePasswordAuthenticationFilter는 인증된 사용자의 정보가 담기는 인증 객체인 Authentication의 종류 중 하나인 UsernamePasswordAuthenticationToken을 만들어 AuthenticationManager에게 넘겨 인증을 시도
    2. 실패하면 SecurityContextHolder를 비운다
    3. 성공하면 SecurityContextHolder에 Authentication를 세팅




SecurityContextHolder

  • SecurityContext는 인증이 완료된 사용자의 상세 정보(Authentication)를 저장
  • SecurityContext는 SecurityContextHolder 로 접근할 수 있다.




Authentication

  • 현재 인증된 사용자를 나타내며 SecurityContext에서 가져올 수 있다.
  • principal : 사용자를 식별
    • Username/Password 방식으로 인증할 때 일반적으로 UserDetails 인스턴스
  • credentials : 주로 비밀번호, 대부분 사용자 인증에 사용한 후 비운다
  • authorities : 사용자에게 부여한 권한을 GrantedAuthority로 추상화하여 사용
🔥 UsernamePasswordAuthenticationToken는 Authentication을 implements한 AbstractAuthenticationToken의 하위 클래스로, 인증객체를 만드는데 사용
  • UserDetailsService 🔥 UserDetailsService는 username/password 인증방식을 사용할 때 사용자를 조회하고 검증한 후 UserDetails를 반환. Custom하여 Bean으로 등록 후 사용 가능

- UserDetails 🔥 검증된 UserDetails는 UsernamePasswordAuthenticationToken 타입의 Authentication를 만들 때 사용되며 해당 인증객체는 SecurityContextHolder에 세팅Custom하여 사용 가능

0개의 댓글