티스토리 뷰

728x90

spring-security-reference.pdf
7.94MB

0. 이미지는 인터넷 검색에서 가져온 내용이다. 개인의 정리 차원에서 작성한 내용이라 신경쓰지 않는다.

 

1. 스프링 보안 2가지로 큰 문제로 나눌 수 있다.

  1-1 인증

  1-2 권한(접근제어)

 

2. 인증 - 스프링은 권한에서 인증을 따로 떼낸 구조이다.

  2-0 인증에 관해 인터넷에 수많은 포스트들이 있는데 아래 링크에서 아래 사진을 가져왔다.

    2-0-1 찾아본 도식 중에서는 제일 좋은 것 같고 이 구조만 알아도 반은 먹고 들어간다.

 

Spring Security : Authentication Architecture

Here is the diagram for demonstrating list of classes and filters involved in spring security authentication process.

springbootdev.com

 

 

 

 

  2-1 가장 중요한 인터페이스는 AuthenticationManager인데, 3가지 중요한 기능을 authenticate 메소드에서 한다.

    2-1-0 authenticate라는 메소드는 Authentication 객체를 받아 실제 인증을 수행한다.

    2-1-1 정상적인 유저, 비밀번호를 받으면 인증 완료 된 Authentication 객체를 반환한다.

      2-1-1-1 Authentication은 인증 토큰 인터페이스라고 할 수 있다. 위의 도식에서는

        2-1-1-1-0 UsernamePasswordAuthenticationToken이 Authentication을 구현하고 있다.

        2-1-1-1-1 하나의 토큰은 사용자에 해당하는 Principal과 비밀번호 Credential을 저장하고, 인증 상태도 저장한다.

        2-1-1-1-2 Principal은 단순히 이름 name만 반환할 수 있는 인터페이스이다.

        2-1-1-1-2 하지만 실제 구현시에는 UsernamePasswordAuthenticationToken 클래스의 경우

          2-1-1-1-2-1 Principal를 객체에 담고 있는데, 스프링 보안에서 사용된 User객체를 통째로 저장한다.

          2-1-1-1-2-2 보통은 UserDetails를 구현한 User객체이다.

 

    2-1-2 맞지 않을 경우 AuthenticationException을 발생

 

    2-1-3 판단할 수 없을 경우는 null을 반환

 

  2-2 AuthenticationException

    2-2-0 runtime exception이다.

    2-2-1 일반적으로 개발자가 처리하지 않고 보통 ControllerAdvice같은 어플리케이션 단에서 처리한다.

    2-2-2 아래 링크 같은 걸 말한다.

 

Spring : REST 전역 예외 처리

1. 직전 포스팅은 각 Controller에 대한 예외처리만 가능하였다. 2. 전역적으로 예외처리를 하려면 별도의 클래스를 생성한다. 2-0 클래스에 @ControllerAdvice를 붙여 Controller에 대한 AOP처리임을 명시한��

kogle.tistory.com

 

  2-3 ProviderManager

    2-3-1 아래 도식도 인터넷에서 찾았다. ProviderManager를 이해하기 좋아서 가져왔다.

    2-3-1 AuthenticationFilter가 인증정보를 AuthenticationManager을 구현하는 ProviderManager에게 넘겨준다.

    2-3-2 ProviderManager는 내부에 AthenticationProvider 목록을 가지고 있어 인증을 다시 위탁한다.

      2-3-2-0 위탁하기 때문에 AuthenticationProvider 인터페이스도 authenticate 메소드가 있다.

      2-3-2-1 추가적으로 어떤 authentication token을 넘겨주면 인증을 지원하는지 확인하는 메소드도 있다.

      2-3-2-2 넘겨준 Authentication을 처리할 수 없으면 false 반환하여 skip되고 다음목록으로 넘어간다.    

      2-3-2-3 처리할 수 있는 AuthenticationProvider가 없으면 AuthenticationException이 발생한다.

 

public interface AuthenticationProvider {

	Authentication authenticate(Authentication authentication)
			throws AuthenticationException;

	boolean supports(Class<?> authentication);

}

 

      2-3-2-4 아래 처럼 ProviderManager는 DAO, CAS, LDAP 등 어려 방식으로 로그인 위탁이 가능하다.

      2-3-2-5 물론 inMemory 방식도 이런 것들 중에 한 가지 방식이다. 

 

 

      2-3-2-6 이런 인증 방식은 각각 다른 uri 그룹으로 지정할 수 있는데,

        2-3-2-6-1 이런 그룹 전체가 공유하는 global provider를 가질 수 있다.

        2-3-2-6-2 아래 도식을 보면 어떤 방식으로 계층화 될 수 있는지 볼 수 있다.

 

 

 

 

  2-4 AthenticationManagerBuilder

    2-4-1 이 helper 클래스는 다양한 종류의 인증방식을 빠르게 세팅하는데 사용한다.

    2-4-2 우리가 많이 보던 아래의 소스가 이 builder를 가지고 부모 ProviderManager를 세팅하는 것이다.

    2-4-3 아래는 최상위 부모 ProviderManager를 설정하는 방법이다.

      2-4-3-1 Autowired되고 있는 AuthenticationManagerBuilder는 최상위 ProviderManager만 생성가능하다.

 

@Configuration
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

   ... // web stuff here

  @Autowired
  public void initialize(AuthenticationManagerBuilder builder, DataSource dataSource) {
    builder.jdbcAuthentication().dataSource(dataSource).withUser("dave")
      .password("secret").roles("USER");
  }

}

 

    2-4-4 로컬에서 사용할 ProviderManager를 생성하고 싶으면 아래처럼 상속 메소드를 Override해야 한다.

 

@Configuration
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

  @Autowired
  DataSource dataSource;

   ... // web stuff here

  @Override
  public void configure(AuthenticationManagerBuilder builder) {
    builder.jdbcAuthentication().dataSource(dataSource).withUser("dave")
      .password("secret").roles("USER");
  }

}

 

    2-4-5 @Autowired로는 최상위 AuthenticationManager(즉, ProviderManager)만 주입할 수 있다.

      2-4-5-1 자식을 노출하기를 원하면 명시적으로 지정해야 가능해 진다.

      2-4-5-2 아래 링크를 보면 명시적으로 빈을 노출하는 내용이 있다.

 

 

Spring Boot : Security 사용하기 기본 Configuration

0. Spring Security를 사용하려면 0-1. Spring Security Dependency를 pom에 등록한다. 0-2. SecurityConfig파일을 생성하여 필요한 Bean을 등록한다. 0-2-0. WebSecurityConfigurerAdapter를 extends해서 간편하..

kogle.tistory.com

 

    2-4-6 스프링 부트는 기본적으로 부모(global) AthenticationManager를 생성해 준다. 보통은 로컬 객체를 사용한다.

      2-4-6-1 거의 부모 인증관리자를 사용하는 일이 없다. 보안측면에서도 좋지 않다.

 

  2-5 SecurityContextHolder

 

 

    2-5-1 유저의  request사이에 SecurityContext가 저장되어야 인증여부를 알 수가 있다.

    2-5-2 일반적인 유저 데이터 유지

      2-5-2-1 보통 웹어플리케이션에서는 사용자가 로그인하면 세션 ID로 사용자를 식별 할 수 있다.

      2-5-2-2 서버는 세션이 유지되는 동안 사용자 정보를 cache에 유지하게 된다.

    2-5-3 Spring Securiy에서의 SecurityContext 관리

      2-5-3-1 SecurityContext는 단순히 Authentication을 저장하는 객체로 생각할 수 있다.

        2-5-3-1-1 내부적으로 getAuthentication, setAthentication 메소드 밖에 없다.

      2-5-3-2 스프링 인증 정보를 사용자의 request 사이에 유지하는 기능은 SecurityContextPersistenceFilter가 가진다. 

        2-5-3-2-1 이 필터는 단순히 HttpSession의 attribute의 하나로 SecurityContext를 저장한다. 그냥 세션에 박는다.

      2-5-3-3 SecurityContextPersistenceFilter는 매 request마다 SecuryContextHolder에 SecurityContext 다시 저장하고

        2-5-3-3-1 요청이 완료되면 다시 삭제해 버린다. 존나 비효율적이다. 보안을 위해서 HttpSession접근을 허용 안함.

 

    2-5-4 stateless 서버의 경우는 HttpSession을 관리하지 않기 때문에 매 request마다 인증을 수행한다. 

 

 

 

728x90
댓글