Home

Published

- 16 min read

[ Spring ] Spring Security

img of [ Spring ] Spring Security

Spring Security란?

Spring Security는 Spring 기반의 애플리케이션의 보안(인증과 권한, 인가 등)을 담당하는 스프링 하위 프레임워크이다. Spring Security는 ‘인증’과 ‘권한’에 대한 부분을 Filter 흐름에 따라 처리하고 있다.

Filter는 Dispatcher Servlet으로 가기 전에 적용되므로 가장 먼저 URL 요청을 받지만, Interceptor는 Dispatcher와 Controller사이에 위치한다는 점에서 적용 시기의 차이가 있다.

Spring Security는 보안과 관련해서 체계적으로 많은 옵션을 제공해주기 때문에 개발자 입장에서는 일일이 보안관련 로직을 작성하지 않아도 된다는 장점이 있다.

이러한 Spring Security의 아키텍쳐는 아래와 같다.

스프링 시큐리티의 특징

  1. 서블릿 API 통합
  2. Spring Web MVC와의 선택적 통합
  3. 인증과 권한 부여를 모두 포괄적이고 확장 가능한 지원
  4. 세션 고정, clickjacking, 사이트 간 요청 위조 등과 같은 공격으로부터 보호

스프링 시큐리티가 요청을 처리하는 방식

스프링 시큐리티는 서블릿 필터체인을 자동으로 구성하고 요청을 거치게 한다.

  1. 유저 로그인 시도 —>AuthenticationFilterHttp servlet Request에서 사용자가 보낸 정보를 intercept한다.
  2. 인증용 객체인 UsernamePasswordAuthenticationToken을 생성한다.
  3. UsernamePasswordAuthenticationTokenAuthenticationManager interface에 위임을 하게 된다. 만약 성공한다면 Authentication 객체를 반환한다.
  4. 반환한 Authentication 객체를 AuthenticationProvider에게 전달한다.
  5. Authentication 객체를 UserDetailsService에 전달한다.
  6. UserDetailsService는 만약 Authentication을 가지로 DB에 있는 User임을 하게 된다면, UserDetails에서 User를 꺼내서 유저 세션을 생성하게 된다.
  7. 가져온 UserDetails를 Spring Sequrity의 인메모리 세션 저장소인 SecurityContextHolder에 저장을 한다.
  8. 이후, 유저 세션ID와 함께 응답을 보내게 된다.

스프링 시큐리티의 주요 구성 요소

이 부분이 복잡해서 어렵다고 느끼는 사람들이 많다. 내용 자체가 이해하기 어렵다기보다는 한번에 이해해야 하는 양이 많아서 어려운 것이다. 아키텍처 기반으로 차근차근 계속 보다보면 그렇게까지 어렵지 않다. 구성 요소들을 차근차근 보자.

Security Context Holder

SecurityContextHolder는 Spring Security의 인증 모델의 핵심이다. 여기에는 SecurityContext가 포함되어 있다. SecurityContextHolder는 현재 인증된 사용자의 세부 정보를 저장한다. Spring Security는 SecurityContextHolder가 어떻게 채워지는지는 신경 쓰지 않는다. 값이 있으면 현재 인증된 사용자로 사용된다.

SecurityContextHolder는 기본적으로 ThreadLocal을 사용하여 정보를 저장한다. 이는 같은 스레드 내에서는 항상 SecurityContext에 접근할 수 있음을 의미한다. 하지만 일부 애플리케이션의 경우 이 방식이 적합하지 않을 수 있다. 이런 경우 SecurityContextHolder.MODE_GLOBAL 또는 SecurityContextHolder.MODE_INHERITABLETHREADLOCAL로 전략을 변경할 수 있다.

Security Context

SecurityContext는 Authentication 객체를 보관한다. SecurityContextHolder로부터 얻을 수 있다.

Authentication

Authentication 인터페이스는 Spring Security에서 두 가지 주요 목적으로 사용된다.

  1. AuthenticationManager에 사용자가 제공한 인증 정보를 제공하는 입력으로 사용된다. 이 경우 isAuthenticated()는 false를 반환한다.
  2. 현재 인증된 사용자를 나타낸다. 현재 Authentication은 SecurityContext에서 얻을 수 있다.

Authentication은 다음 정보를 포함한다.

  • principal: 사용자를 식별한다. 사용자명/비밀번호로 인증할 때 보통 UserDetails의 인스턴스다.
  • credentials: 주로 비밀번호. 대부분의 경우 사용자 인증 후 지워진다.
  • authorities: GrantedAuthority 인스턴스로, 사용자에게 부여된 고수준 권한이다.
   public interface Authentication extends Principal, Serializable {
    // 현재 사용자의 권한 목록을 가져옴
    Collection<? extends GrantedAuthority> getAuthorities();

    // credentials(주로 비밀번호)을 가져옴
    Object getCredentials();

    Object getDetails();

    // Principal 객체를 가져옴.
    Object getPrincipal();

    // 인증 여부를 가져옴
    boolean isAuthenticated();

    // 인증 여부를 설정함
    void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;
}

UserNameAuthenticationToken

UsernamePasswordAuthenticationToken은 Authentication을 implements한 AbstractAuthenticationToken의 하위 클래스로, User의 ID가 Principal 역할을 하고, Password가 Credential의 역할을 한다. UsernamePasswordAuthenticationToken의 첫 번째 생성자는 인증 전의 객체를 생성하고, 두번째 생성자는 인증이 완료된 객체를 생성한다.

   public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {
    // 주로 사용자의 ID에 해당함
    private final Object principal;
    // 주로 사용자의 PW에 해당함
    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
	}
}


public abstract class AbstractAuthenticationToken implements Authentication, CredentialsContainer {
}

AuthenticationProvider

AuthenticationProvider에서는 실제 인증에 대한 부분을 처리하는데, 인증 전의 Authentication객체를 받아서 인증이 완료된 객체를 반환하는 역할을 한다. 아래와 같은 AuthenticationProvider 인터페이스를 구현해서 Custom한 AuthenticationProvider을 작성해서 AuthenticationManager에 등록하면 된다.

   public interface AuthenticationProvider {

	// 인증 전의 Authenticaion 객체를 받아서 인증된 Authentication 객체를 반환
    Authentication authenticate(Authentication var1) throws AuthenticationException;

    boolean supports(Class<?> var1);

}

AuthenticationManager

AuthenticationManager는 Spring Security의 필터가 인증을 수행하는 방법을 정의하는 API다. 반환된 Authentication은 AuthenticationManager를 호출한 컨트롤러(Spring Security의 Filters)에 의해 SecurityContextHolder에 설정된다.

가장 일반적인 AuthenticationManager 구현체는 ProviderManager다.

인증에 대한 부분은 SpringSecurity의 AuthenticatonManager를 통해서 처리하게 되는데, 실질적으로는 AuthenticationManager에 등록된 AuthenticationProvider에 의해 처리된다. 인증이 성공하면 2번째 생성자를 이용해 인증이 성공한(isAuthenticated=true) 객체를 생성하여 Security Context에 저장한다. 그리고 인증 상태를 유지하기 위해 세션에 보관하며, 인증이 실패한 경우에는 AuthenticationException를 발생시킨다.

   public interface AuthenticationManager {
	Authentication authenticate(Authentication authentication)
		throws AuthenticationException;
}

AuthenticationManager를 implements한 ProviderManager는 실제 인증 과정에 대한 로직을 가지고 있는 AuthenticaionProvider를 List로 가지고 있으며, ProividerManager는 for문을 통해 모든 provider를 조회하면서 authenticate 처리를 한다.

   public class ProviderManager implements AuthenticationManager, MessageSourceAware,
InitializingBean {
    public List<AuthenticationProvider> getProviders() {
		return providers;
	}
    public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		Class<? extends Authentication> toTest = authentication.getClass();
		AuthenticationException lastException = null;
		Authentication result = null;
		boolean debug = logger.isDebugEnabled();
        //for문으로 모든 provider를 순회하여 처리하고 result가 나올 때까지 반복한다.
		for (AuthenticationProvider provider : getProviders()) {
            ....
			try {
				result = provider.authenticate(authentication);

				if (result != null) {
					copyDetails(authentication, result);
					break;
				}
			}
			catch (AccountStatusException e) {
				prepareException(e, authentication);
				// SEC-546: Avoid polling additional providers if auth failure is due to
				// invalid account status
				throw e;
			}
            ....
		}
		throw lastException;
	}
}

위에서 설명한 ProviderManager에 우리가 직접 구현한 CustomAuthenticationProvider를 등록하는 방법은 WebSecurityConfigurerAdapter를 상속해 만든 SecurityConfig에서 할 수 있다. WebSecurityConfigurerAdapter의 상위 클래스에서는 AuthenticationManager를 가지고 있기 때문에 우리가 직접 만든 CustomAuthenticationProvider를 등록할 수 있다.

   @Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public AuthenticationManager getAuthenticationManager() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public CustomAuthenticationProvider customAuthenticationProvider() throws Exception {
        return new CustomAuthenticationProvider();
    }

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

ProviderManager

ProviderManager는 AuthenticationManager의 가장 일반적인 구현체이다. ProviderManager는 AuthenticationProvider 목록에 인증을 위임한다. 각 AuthenticationProvider는 인증을 시도하고, 성공, 실패를 반환하거나 결정할 수 없음을 표시하고 다음 AuthenticationProvider가 결정하도록 할 수 있다.

만약 구성된 AuthenticationProvider 중 어느 것도 인증에 성공하지 못하면, 인증은 ProviderNotFoundException과 함께 실패한다. ProviderNotFoundException은 ProviderManager가 주어진 Authentication 타입을 지원하도록 구성되지 않았음을 나타내는 특별한 AuthenticationException이다.

ProviderManager는 또한 선택적으로 부모 AuthenticationManager를 가질 수 있다. 부모는 어떤 AuthenticationManager의 구현체도 될 수 있지만, 보통 ProviderManager의 또 다른 인스턴스이다. 만약 인증이 실패하면, ProviderManager는 부모 AuthenticationManager에게 인증을 시도하도록 요청할 것이다.

기본적으로 ProviderManager는 성공적인 인증 요청 후 반환된 Authentication 객체로부터 민감한 인증 정보를 제거하려고 시도한다. 이는 비밀번호와 같은 정보가 HttpSession에 필요 이상으로 유지되는 것을 방지한다.

AuthenticationEntryPoint

AuthenticationEntryPoint는 클라이언트에게 인증 정보를 요청할 때 사용된다. 일반적으로 로그인 페이지로 리다이렉트하거나, WWW-Authenticate 헤더를 보내는 등의 역할을 한다.

AbstractAuthenticationProcessingFilter

AbstractAuthenticationProcessingFilter는 사용자의 인증 정보를 인증하는 기본 필터다. 인증 정보가 인증되기 전에 Spring Security는 보통 AuthenticationEntryPoint를 사용하여 인증 정보를 요청한다.

UserDetails

인증에 성공하여 생성된 UserDetails 객체는 Authentication객체를 구현한UsernamePasswordAuthenticationToken을 생성하기 위해 사용된다. UserDetails 인터페이스를 살펴보면 아래와 같이 정보를 반환하는 메소드를 가지고 있다. UserDetails 인터페이스의 경우 직접 개발한 UserVO 모델에 UserDetails를 implements하여 이를 처리하거나 UserDetailsVO에 UserDetails를 implements하여 처리할 수 있다.

   public interface UserDetails extends Serializable {

    Collection<? extends GrantedAuthority> getAuthorities();

    String getPassword();

    String getUsername();

    boolean isAccountNonExpired();

    boolean isAccountNonLocked();

    boolean isCredentialsNonExpired();

    boolean isEnabled();

}

UserDetailsService

UserDetailsService 인터페이스는 UserDetails 객체를 반환하는 단 하나의 메소드를 가지고 있는데, 일반적으로 이를 구현한 클래스의 내부에 UserRepository를 주입받아 DB와 연결하여 처리한다. UserDetails 인터페이스는 아래와 같다.

   public interface UserDetailsService {

    UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException;

}

Password Encoding

AuthenticationManagerBuilder.userDetailsService().passwordEncoder() 를 통해 패스워드 암호화에 사용될 PasswordEncoder 구현체를 지정할 수 있다.

   @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
	// TODO Auto-generated method stub
	auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}

@Bean
public PasswordEncoder passwordEncoder(){
	return new BCryptPasswordEncoder();
}

Granted Authority

GrantAuthority는 현재 사용자(principal)가 가지고 있는 권한을 의미한다. ROLEADMIN나 ROLE_USER와 같이 ROLE*의 형태로 사용하며, 보통 “roles” 이라고 한다. GrantedAuthority 객체는 UserDetailsService에 의해 불러올 수 있고, 특정 자원에 대한 권한이 있는지를 검사하여 접근 허용 여부를 결정한다.

시큐리티의 주요 필터

SecurityContextPersistenseFilter

  • SecurityContextRepository를 통해 SecurityContext를 Load/Save 처리

LogoutFilter

  • 로그아웃 URL(기본값: /logout)로의 요청을 감시하여 해당 사용자를 로그아웃 시킴

UsernamePasswordAuthenticationFilter

  • ID/PW 기반 Form 인증 요청 URL(기본값: /login)을 감시하여 사용자를 인증함

ExceptionTransiationFilter

  • 요청을 처리하는 중에 발생할 수 있는 예외를 위임하거나 전달

FilterSecurityInterceptor

  • 접근 권한 확인을 위해 요청을 AccessDecisionManager로 위임. 이 필터가 실행되는 시점에는 사용자가 인증됐다고 판단
   @Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .cors() // CORS 설정 활성화
    .and()
        .sessionManagement() // 세션 관리 설정
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 세션 생성 정책을 Stateless로 설정
    .and()
        .csrf().disable() // CSRF 방지 기능 비활성화
        .formLogin().disable() // 폼 로그인 기능 비활성화
        .httpBasic().disable() // 기본 HTTP 인증 기능 비활성화
        .exceptionHandling() // 예외 처리 설정
        .authenticationEntryPoint(new RestAuthenticationEntryPoint()) // 사용자 정의 인증 진입점 설정
        .accessDeniedHandler(tokenAccessDeniedHandler) // 사용자 정의 접근 거부 핸들러 설정
    .and()
        .authorizeRequests() // 요청 인증 설정
        .requestMatchers(CorsUtils::isPreFlightRequest).permitAll() // CORS 전처리 요청에 대해 인증을 허용
        .antMatchers("/api/**").hasAnyAuthority(RoleType.USER.getCode()) // "/api/**" 패턴의 URL에 USER 권한이 있는 경우 접근 허용
        .antMatchers("/api/**/admin/**").hasAnyAuthority(RoleType.ADMIN.getCode()) // "/api/**/admin/**" 패턴의 URL에 ADMIN 권한이 있는 경우 접근 허용
        .anyRequest().authenticated() // 나머지 요청은 모두 인증 받은 사용자만 접근 가능
    .and()
        .oauth2Login() // OAuth2 로그인 설정
        .authorizationEndpoint()
        .baseUri("/oauth2/authorization") // 인증 엔드포인트 기본 URI 설정
        .authorizationRequestRepository(oAuth2AuthorizationRequestBasedOnCookieRepository()) // 사용자 정의 인증 요청 저장소 설정
    .and()
        .redirectionEndpoint() // 리다이렉션 엔드포인트 설정
        .baseUri("/*/oauth2/code/*") // 리다이렉션이 발생하는 기본 URI 설정
    .and()
        .userInfoEndpoint() // 사용자 정보 엔드포인트 설정
        .userService(oAuth2UserService) // 사용자 정보 서비스 설정
    .and()
        .successHandler(oAuth2AuthenticationSuccessHandler()) // OAuth2 인증 성공 핸들러 설정
        .failureHandler(oAuth2AuthenticationFailureHandler()); // OAuth2 인증 실패 핸들러 설정

    http.addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); // 사용자 정의 필터를 필터 체인에 추가
}