[Spring] Spring Security (2) 주요 컴포넌트

hyewon jeong·2023년 1월 4일
0

Spring

목록 보기
18/59

🍃 2. Spring Security 주요 컴포넌트

Spring Security와 Filter

💜 스프링 시큐리티는 요청이 들어오면 Servlet Filter Chain을 자동으로 구성한 후 거치게 된다.
Filter는 Client요청이 전달되기 전후의 URL패턴에 맞는 모든 요청에 필터링 역할을 한다.
예) CSRF, XSS 등 보안 검사를 통해 올바른 요청이 아닐 경우 이를 차단 한다.
이런 기능을 활용하여 스프링시큐리티에서 filter를 사용하여 인증/인가를 구현한다.

SecurityFilterChain

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

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


일반적인 Spring Security의 인증 과정은 다음과 같습니다:

  1. 클라이언트로부터 인증 요청이 들어옵니다.
  2. UsernamePasswordAuthenticationFilter가 요청을 가로채어 사용자가 입력한 인증 정보를 확인합니다.
  3. AuthenticationManager를 통해 사용자 인증을 수행합니다.
  4. 인증이 성공하면 Authentication 객체가 생성됩니다.
  5. Authentication 객체는 SecurityContextHolder에 저장되어 현재 인증된 사용자 정보를 관리합니다.
  6. 요청은 다음 필터로 계속 전달됩니다.

아래는 Security Filter 들의 실행 순서입니다.

- SecurityContextHolder에는 스프링 시큐리티로 인증한 사용자의 상세정보를 저장한 Authentication객체를 저장한 SecurityContext를 담고 있다.

  • SecurityContext ? SecurityContextHolder로 접근 가능 ,Authentication객체 가지고 있음

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

    • principal : 사용자를 식별한다. Username/password방식으로 인증할 때 보통 UserDetails 인스턴스다.
    • credential : 주로 비밀번호, 대부분 사용자 인증에 사용되고 다음에 비운다.
    • authorities : 사용자에게 부여한 권한을 GrantedAuthority로 추상화하여 사용한다.
		<UserDetails>
		@Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        UserRoleEnum role = user.getRole();
        String authority = role.getAuthority();
        System.out.println("authority = " + authority);

        SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authority);
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(simpleGrantedAuthority);

        return authorities;
    }

Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
  • UsernamePasswordAuthenticationToken는 Authentication을 implements한 AbstractAuthenticationToken의 하위 클래스로 , 인증객체를 만드는데 사용된다. \

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

profile
개발자꿈나무

0개의 댓글