Spring Security 개념정리

suesue lee·2022년 1월 30일
0

SPRING

목록 보기
4/4

1. Spring Security란?

  • Spring Security 란 Spring 기반의 application의 보안 (인증과 권한, 인가 등)을 담당하는 Spring 하위 framework 이다.
  • Spring Security 는 "인증"과 "권한"에 대한 부분을 Filter 의 흐름에 따라 처리한다.
  • Spring Security 는 보안과 관련해서 체계적으로 많은 옵션을 제공해주기 때문에 개발자 입장에서 일일이 보안 관련 로직을 작성하지 않아도 된다는 장점이 있다.

(https://images.velog.io/images/tololong001/post/b7cb6e79-d6ea-40a7-ae55-baad03317216/image.png)
< 상위 그림은 Spring Security 의 흐름이다. >


2. 인증과 인가란?

  • 인증 (Authentication)
    : 해당 사용자가 본인이 맞는지를 확인하는 절차이다.

  • 인가 (Authorization)
    : 인증 된 사용자가 요청한 자원에 접근 가능한지를 결정하는 절차

  • Spring Security 는 기본적으로 인증 절차를 거친 후에 인가 절차를 진행하게 되며, 인가 과정에서 해당 리소스에 대한 접근 권한이 있는지 확인한다.
  • 이러한 인증과 인가를 위해 Principal 을 아이디로, Credential 을 비밀번호로 사용하는 Credential 기반의 인증 방식 을 사용한다.
  • Principal (접근 주체) : 보호 받는 리소스에 접근하는 대상
  • Credentail (비밀번호) : 리소스에 접근하는 대상의 비밀번호

Spring Security 의 주요 모듈

Authentication (인증)

  • Authentication 은 현재 접근하는 주체의 정보와 권한을 담는 interface 이다.
  • SecurityContext 에 저장되며, SecurityContextHolder 를 통해 SecurityContext 에 접근하고, SecurityContext 를 통해 Authentication 에 접근할 수 있다.

SecurityContext (보안 컨텍스트)

  • Autentication 을 보관하는 역할을 하며, SecurityContext 를 통해 Autentication 객체를 꺼내올 수 있다.

SecurityContextHolder (내부 메모리)

  • SecurityContextHolder 는 보안 주체의 세부 정보를 포함하여 응용 프로그램의 현재 보안 컨텍스트에 대한 세부 정보가 저장된다.

Spring Security 에서의 인증 처리 과정

  • usernamepassword 를 조합해서 UsernamePasswordAuthenticationToken 인스턴스를 생성한다.
  • 이 토큰을 검증하기 위해 AuthenticationManager 는 인증에 성공하면 Authentication 인스턴스를 return한다.
  • Authentication 인스턴스는 SecurityContextHolder 에 저장한다.

UsernamePasswordAuthenticationToken (인증관련 토큰)

  • AuthenticationimplementAbstractAutheniicationToken 의 하위 클래스로 usernamePrincipal 의 역할을 하고, passwordCredential 의 역할을 한다.
  • 첫번째 생성자는 인증 전의 객체를 생성하고, 두번째 생성자는 인증이 완료된 객체를 생성해준다.
public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {
    // 주로 사용자의 username에 해당함
    private final Object principal;
    // 주로 사용자의 password에 해당함
    private Object credentials;
    
    // 인증 완료 전의 객체 생성
    public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
		super(null);
		this.principal = principal;
		this.credentials = credentials;
		setAuthenticated(false);
	}
    
    // 인증 완료 후의 객체 생성
    public UsernamePasswordAuthenticationToken(Object principal, Object credentials,
			Collection<? extends GrantedAuthority> authorities) {
		super(authorities);
		this.principal = principal;
		this.credentials = credentials;
		super.setAuthenticated(true); // must use super, as we override
	}
}

AuthenticationProvider (인증 제공자)

  • 실제 인증에 대한 부분을 처리하는데, 인증 전의 Authentication 객첼,르 받아서 인증이 완료된 객체를 반환하는 역할이다.

AuthenticationManager (인증 관리자)

  • 인증에 대한 부분은 AuthenticationManager 를 통해서 처리하게 되는데, 실질적으로는 AuthenticationManager 에 등록된 AuthenticationProvider 에 의해서 처리된다.
  • 인증이 성공하면 isAuthenicated = true 인 객체를 생성하여 SecurityContext 에 저장한다.
  • 실패할 경우 AuthenticationException 을 발생시킨다.
  • DaoAuthenticationProviderAbstracUserDetailsAuthenticationProvider 를 상속받아 실제 인증 과정에 대한 로직을 처리한다.
  • AuthenticationManagerDaoAuthenticationProvider 를 등록하는 방법은 WebSecurityConfigureAdaper 를 상속해 만든 ApplicationSecurityConfig 에서 할 수 있다.
@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {

  private final PasswordEncoder passwordEncoder;

  @Autowired
  public ApplicationSecurityConfig(PasswordEncoder passwordEncoder,) {
    this.passwordEncoder = passwordEncoder;
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(daoAuthenticationProvider());
  }

  @Bean
  public DaoAuthenticationProvider daoAuthenticationProvider() {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setPasswordEncoder(passwordEncoder);
    provider.setUserDetailsService(applicationUserService);

    return provider;
  }
}

UserDetails

  • 인증에 성공하여 생성된 UserDetails 객체는 UsernamePasswordAuthenticationToken 을 생성하기 위해 사용된다.
  • UserDetails interface 의 경우 직접 개발한 ApplicationUserUserDetails 를 implements 하여 사용하면 된다.

UserDetailsService

  • UserDetails 객체를 반환하는 단 하나의 메소드를 가지고 있다.
    일반적으로 이를 구현한 클래스의 내부에 UserRespository를 주입 받아 DB에 연결하여 처리된다.

GrandtedAuthority

  • 현재 사용자 (Principal) 가 가지고 있는 권한들이다.
  • 보통 ROLE_ADMIN, ROLE_USER, ROLE_ 의 형태로 사용된다.

출처 : https://velog.io/@dnjscksdn98/Spring-Spring-Security%EB%9E%80

profile
미래의 웹프로그래머

0개의 댓글