[Spring] Spring Security

Jeon817·2023년 4월 25일

Spring

목록 보기
7/11

[Spring Security 란?]

  • Spring Security 는 Filter 를 기반으로 동작하면서 스프링 서버에 필요한 인증 및 인가를 위해 많은 기능을 제공해주는 스프링 하위 프레임워크라고 할 수 있습니다.

[Spring Security 사용하는 이유]

1) 모든 URL에 대해서 인증을 요구한다.
2) 로그인 폼을 생성한다.
3) 기초적인 폼에 대해서 사용자 이름과 비밀번호를 요구한다.
4) 사용자에 대한 로그아웃 기능도 있다.
5) CSRF(Cross Site Request Forgery) 공격을 방어한다.
6) Session Fixsation을 방어한다.
7) 요청 헤드 보안
8) Servlet API 제공

Spring Security 는 위와 같이 인증/인가에 필요한 많은 기능들을 제공하기 때문에 개발자들의 입장에서 저러한 기능들을 일일이 다 구현할 필요 없이 Spring Security 를 적용시킴으로써 보안적인 측면도 개선하고 개발 시간을 절약할 수 있기 때문입니다.

[Spring Security 주요 컴포넌트]

  • Spring Security 와 Filter

    • Spring Security는 요청이 들어오면 Servlet FilterChain을 자동으로 구성한 후 거치게 한다. FilterChain은 여러 Filter를 chain형태로 묶어놓은 것을 의미합니다. 여기서 Filter 란, 톰캣과 같은 웹 컨테이너에서 관리되는 서블릿의 기술이다. Filter는 Client 요청이 전달되기 전후의 URL 패턴에 맞는 모든 요청에 필터링을 해준다. CSRF, XSS 등의 보안 검사를 통해 올바른 요청이 아닐 경우 이를 차단해 준다. 따라서 Spring Security는 이런한 기능을 활용하기위해 Filter를 사용하여 인증/인가를 구현하고 있다.
  • SecurityFilterChain

    • Spring 의 보안 Filter를 결정하는데 사용되는 Filter session, jwt 등의 인증방식들을 사용하는데에 필요한 설정을 완전히 분리할 수 있는 환경을 제공한다.
  • AbstractAuthenticationProcessingFilter

    • 사용자의 credential을 인증하기 위한 베이스 Filter
  • UsernamePasswordAuthenticationFilter

    • UsernamePasswordAuthenticationFilter 는 AbstractAuthenticationProcessingFilter를 상속한 Filter다. 기본적으로 아래와 같은 Form Login 기반을 사용할 때 username 과 password 확인하여 인증한다. Form Login 기반은 인증이 필요한 URL 요청이 들어왔을 때 인증이 되지 않았다면 로그인페이지를 반환하는 형태이다.
  • SecurityContextHolder

    • SecurityContextHolder 에는 스프링 시큐리티로 인증을 한 사용자의 상세 정보를 저장한다.
    • SecurityContext 란? SecurityContextHolder 로 접근할 수 있으며 Authentication 객체를 가지고 있다.
  • Authentication

    • 현재 인증된 사용자를 나타내며 SecurityContext 에서 가져올 수 있다.

    • Principal : User의 식별자로, User Id, Email과 같은 정보를 담고 있는 객체입니다.

    • Credentials : Password와 같은 중요한 정보로, 유출방지를 위해 보통 인증된 이후에는 삭제됩니다.

    • Authorities : 권한 정보로, 보통 Role 혹은 Scope(어떤 걸 수행할수 있는지)로 설정을 합니다.

      // Authentication 설정 예시코드
      SecurityContext context = SecurityContextHolder.createEmptyContext();
      Authentication authentication = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
      context.setAuthentication(authentication);
      
      SecurityContextHolder.setContext(context);

    UsernamePasswordAuthenticationTokend은 Authentication을 implements한 AbstractAuthenticationToken의 하위 클래스로, 인증객체를 만드는데 사용된다. SecurityContext는 이 Authentication 객체를 담는 Container 역할을하고, SecurityContextHolder는 다시 SecurityContext 를 관리하는 역할을 한다고 볼 수 있습니다.

  • UserDetailsService

    • UserDetailsService는 username/password 인증방식을 사용할 때 사용자를 조회하고 검증한 후 UserDetails를 반환한다. Custom하여 Bean으로 등록 후 사용 가능하다.
  • UserDetails

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



[Spring Security 인증 처리 흐름]

[참고]https://somuchthings.tistory.com/197

0개의 댓글