Spring Security

Yeseong31·2023년 8월 29일
0
post-thumbnail

Spring Boot 3.0부터는 Spring Security 6+을 사용한다.
하지만 Spring Boot 2.x.x 버전과 비교했을 때 사용 및 설정 방식이 많이 달라졌다.

여기서는 구현에 앞서 먼저 Spring Security가 무엇인지 살펴본다.


Spring Security란?

Spring Security는 Spring에서 제공하는 인증과 인가에 대한 처리를 위임하는 별도로 프레임워크이다.

  • Spring Security는 인증권한에 대한 부분을 필터의 흐름에 따라 처리한다.

  • 필터DispatcherServler 전에 적용되기 때문에 가장 먼저 URL을 받는다.
  • 인터셉터DispatcherServletController 사이에 위치한다.
  • 필터와 인터셉터는 적용되는 시기가 다르다.

인증과 인가

인증(Authentication)은 해당 사용자가 본인이 맞는지 확인하는 절차이다.
인가(Authorization)는 인증된 사용자가 요청한 자원에 접근할 수 있는지를 결정하는 절차이다.

  • Spring Security는 기본적으로 인증을 거친 후에 인가를 진행한다.
  • Spring Security에서는 이러한 인증과 인가를 위해 Credential 기반의 인증 방식을 사용한다.
  • Credential 기반의 인증 방식에서는 PrincipalCredential이라는 개념이 등장한다.
    • Principal은 접근 주체, 리소스에 접근하는 대상을 말하며 주로 아이디로 사용한다.
    • Credential은 리소스에 접근하는 대상의 비밀번호로 사용한다.

필터와 필터 체이닝

Spring Security 내부에는 여러 개의 필터가 필터 체이닝(Filter Chaining) 구조로 request를 처리한다.

  • 일반적인 필터는 스프링 빈을 사용할 수 없어서 별도의 클래스를 상속받는 형태가 많다.
  • 하지만 Spring Security에서의 필터스프링 빈과 연동할 수 있는 구조를 가진다.

인증을 위한 AuthenticationManager

필터의 핵심적인 동작은 AuthenticationManager를 통해 인증을 의미하는 Authentication 객체로 작업을 하게 된다.

  • AuthenticationManager가 가지는 인증 처리 메서드는 파라미터와 리턴 타입 모두 Authentication 객체이다.
  • 실제 동작에서 전달되는 파라미터는 UsernamePasswordAuthenticationToken이며, 이는 Spring Security 필터의 주요 역할이 인증 관련 정보를 토큰이라는 객체로 만들어서 전달한다는 의미를 가진다.

아래 Spring Security 동작 과정을 살펴보자.




Spring Security 동작 과정

1. 사용자가 로그인에 필요한 아이디, 비밀번호 등을 통해 로그인을 요청한다.

2. AuthenticationFilter가 로그인 정보를 인터셉트한다.

  • 인터셉트한 정보를 가지고 UsernamePasswordAuthenticationToken(Authentication) 객체를 생성한다.
  • 생성된 Authentication 객체는 인증 전의 객체이며 AuthenticationManager로 전달된다.

3. AuthenticationManager 인터페이스를 거쳐서 AuthenticationProvider에게 Authentication 형태의 정보를 전달한다.

  • 등록된 AuthenticationProvider들을 조회하면서 인증을 요구한다.

4. AuthenticationProviderUserDetailsService를 통해 입력 받은 정보를 데이터베이스에서 조회한다.

  • supports() 메서드로 실행 가능한지 먼저 확인을 한다.
  • 이후 authenticate() 메서드로 DB 사용자 정보와 로그인 정보를 비교한다.
  • 이때 DB 사용자 정보는 UserDetailsServiceloadUserByUsername() 메서드로 가져온다.
  • 비교한 정보가 일치하는 경우에는 Authentication 객체를 반환한다.

5. AuthenticationManagerAuthentication 객체를 AuthenticationFilter로 전달한다.

6. AuthenticationFilter는 전달 받은 Authentication 객체를 LoginSuccessHandler로 전달한다.

  • 이때 Authentication 객체는 SecurityContextHolder에 담기게 된다.

7. 인증이 성공적으로 완료되면 AuthenticationSuccessHandle을 실행하고, 그렇지 않으면 AuthenticationFailureHandle을 실행한다.




Spring Security 모듈

SecurityContextHolder

  • 현재 보안 컨텍스트에 대한 세부 정보가 저장된다.
  • 기본적으로 SecurityContextHolder.MODE_INHERITABLETHREADLOCAL 방식과 SecurityContextHolder.MODE_THREADLOCAL 방식을 제공한다.

SecurityContext

public interface SecurityContext extends Serializable {

	Authentication getAuthentication();

	void setAuthentication(Authentication authentication);
}
  • Authentication을 보관하는 역할을 한다.
  • SecurityContext를 통해 Authentication 객체를 가져올 수 있다.

Authentication

public interface Authentication extends Principal, Serializable {

	// 현재 사용자 권한 목록 조회
	Collection<? extends GrantedAuthority> getAuthorities();

	// credential(비밀번호) 조회
	Object getCredentials();

	Object getDetails();

	// Principal(접근 주체) 조회
	Object getPrincipal();

	// 인증 여부 확인
	boolean isAuthenticated();

	// 인증 여부 설정
	void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException;
}
  • Authentication 객체는 현재 접근 주체의 정보와 권한을 담은 인터페이스이다.
  • Authentication 객체는 SecurityContext에 저장된다.
  • SecurityContextHolder를 통해 SecurityContext에 접근하고, SecurityContext를 통해 Authentication에 접근할 수 있다.

위에서 설명한 Spring Security 동작 과정 그림을 보면 이해가 될 것이다.


UsernamePasswordAuthenticationToken

public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {

	// 사용자 ID와 비슷
	private final Object principal;

	// 사용자 비밀번호와 비슷
	private Object credentials;

	// 인증 완료 전의 Authentication 객체 생성
	public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {

		super(null);
		this.principal = principal;
		this.credentials = credentials;
		setAuthenticated(false);
	}

	// 인증 완료 후의 Authentication 객체 생성
	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
	}

	...

	@Override
	public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {

		Assert.isTrue(!isAuthenticated, "Cannot set this token to trusted ...");
		super.setAuthenticated(false);
	
	}
}

...

public abstract class AbstractAuthenticationToken implements Authentication, CredentialsContainer { ... }
  • UsernamePasswordAuthenticationTokenAuthenticationimplementsAbstractAuthenticationToken의 하위 클래스이다.
  • 사용자 ID를 의미하는 Principal, 사용자 비밀번호를 의미하는 Credential이 있다.
  • UsernamePasswordAuthenticationToken의 첫 번째 생성자는 인증 전의 객체를 생성하고, 두 번째 생성자는 인증 후의 객체를 생성한다.

AuthenticationProvider

public interface AuthenticationProvider {

	Authentication authenticate(Authentication authentication)  throws AuthenticationException;

	boolean supports(Class<?> authentication);
}
  • AuthenticationProvider에서는 실제 인증에 대한 부분을 처리한다.
  • AuthenticationManager로부터 전달 받은 인증 전Authentication 객체를 받아서 인증이 완료된 Authentication 객체를 반환한다.
  • 위의 AuthenticationProvider 인터페이스를 구현해서 개발에 필요한 AuthenticationProvider를 작성하고, AuthenticationManager에 등록하면 된다.

AuthenticationManager

Spring Security의 핵심 역할AuthenticationManager에서 이루어진다.

public interface AuthenticationManager {

	Authentication authenticate(Authentication authentication) throws AuthenticationException;
}
  • 인증에 대한 부분은 AuthenticationManager를 통해 처리한다.
    • 실질적으로는 AuthenticationManager에 등록된 AuthenticationProvider에 의해 처리된다.
  • 인증에 성공하면 UsernamePasswordAuthenticationToken의 두 번째 생성자를 통해 인증이 성공한 객체를 생성한다.
    • 생성된 객체는 SecurityContext에 저장된다.
    • 인증 상태를 유지하기 위해 세션에 보관하며, 인증에 실패하면 AuthenticationException이 발생한다.

ProviderManager

public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean {

	public List<AuthenticationProvider> getProviders() {
		return this.providers;
	}

	...

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {

		Class<? extends Authentication> toTest = authentication.getClass();
		AuthenticationException lastException = null;
		AuthenticationException parentException = null;
		Authentication result = null;
		Authentication parentResult = null;

		...
		
		// 모든 provider를 순회하면서 처리하고 result가 나올 때까지 반복 
		for (AuthenticationProvider provider : getProviders()) {
			try {
				result = provider.authenticate(authentication);

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

			...
		}
		
		...

		throw lastException;
	}
}
  • ProviderManagerAuthenticationManagerimplements했다.
  • 실제 인증 과정에 대한 로직을 가지고 있는 AuthenticationProviderList로 가지고 있다.
  • for 문을 돌면서 모든 provider를 조회하고, 인증 처리를 한다.

ProviderManager에 개발자가 직접 구현한 CustomAuthenticationProvider를 등록하는 방법은 WebSecurityConfigurerAdapter를 상속하여 만든 SecurityConfig에서 진행할 수 있다.

@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 confiture(AuthenticationManagerBuilder auth) throws Exception {

		auth.authenticationProvider(customAuthenticationProvider());
	}
}

WebSecurityConfigurerAdapter의 상위 클래스에서는 AuthenticationManager를 가지고 있기 때문에 개발자가 직접 만든 CustomAuthenticationProvider를 등록할 수 있다.


UserDetails

public interface UserDetails extends Serializable {
	
	Collection<? extends GrantedAuthority> getAuthorities();
	
	String getPassword();

	String getUsername();
	
	boolean isAccountNonExpired();

	boolean isAccountNonLocked();

	boolean isCredentialsNonExpired();
		
	boolean isEnabled();
}
  • 인증에 성공한 뒤에 생성된 UserDetails 객체는 Authentication 객체를 구현한 UsernamePasswordAuthenticationToken을 위해 사용된다.
  • UserDetails 인터페이스는 사용자의 정보를 담는 인터페이스이다.
  • 따라서 사용자 정보를 불러오는 역할을 하는 메서드들이 여럿 정의되어 있다.

UserDetails 인터페이스는 주로 개발자가 직접 개발한 CustomUserDetailsimplements하여 사용한다.


UserDetailsService

AuthenticationProvider에서 AuthenticationManager가 어떻게 동작해야 하는지를 결정한다면, 실제 인증은 UserDetailsService에서 이루어진다.

public interface UserDetailsService {

	UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}
  • UserDetailsService 인터페이스는 UserDetails 객체를 반환하는 단 하나의 메서드, loadUserByUsername()을 가지고 있다.
  • 일반적으로 UserDetailsService를 구현한 클래스 내부에 UserRepository를 주입 받아서 DB와 연결하여 처리한다.

GrantedAuthority

public interface GrantedAuthority extends Serializable {

	String getAuthority();
}
  • GrantedAuthority현재 사용자(principal)가 가지고 있는 권한을 말한다.
  • 일반적으로 ROLE_USER, ROLE_ADMIN과 같이 접두사로 ROLE_이 붙는다.
  • GrantedAuthority 객체는 UserDetailsService에 의해 불릴 수 있고, 특정 자원에 대한 권한이 있는지를 검사하는 역할을 한다.

PasswordEncoder

public interface PasswordEncoder {

	// 비밀번호를 단방향 암호화
	String encode(CharSequence rawPassword);

	// 암호화되지 않은 비밀번호와 암호화된 비밀번호의 일치 여부 확인
	boolean matches(CharSequence rawPassword, String encodedPassword);

	// 암호화된 비밀번호를 다시 암호화할 경우에는 return true로 변경
	default boolean upgradeEncoding(String encodedPassword) {
		return false;
	}
}

Spring Boot 2.0부터는 인증을 위해 반드시 PasswordEncoder를 지정해야 한다.

  • PasswordEncoder비밀번호의 단방향 암호화를 지원하는 인터페이스이다.
  • Spring Security에서는 다양한 종류의 PasswordEncoder 구현체를 제공하고 있다.
    • 그 중에서 가장 많이 사용하는 것은 BCryptPasswordEncoder이다.
profile
역시 개발자는 알아야 할 게 많다.

0개의 댓글

관련 채용 정보