
Spring Boot 3.0부터는 Spring Security 6+을 사용한다.
하지만 Spring Boot 2.x.x 버전과 비교했을 때 사용 및 설정 방식이 많이 달라졌다.여기서는 구현에 앞서 먼저 Spring Security가 무엇인지 살펴본다.
Spring Security는 Spring에서 제공하는 인증과 인가에 대한 처리를 위임하는 별도로 프레임워크이다.

DispatcherServler 전에 적용되기 때문에 가장 먼저 URL을 받는다.DispatcherServlet과 Controller 사이에 위치한다.인증(Authentication)은 해당 사용자가 본인이 맞는지 확인하는 절차이다.
인가(Authorization)는 인증된 사용자가 요청한 자원에 접근할 수 있는지를 결정하는 절차이다.
Principal과 Credential이라는 개념이 등장한다.Principal은 접근 주체, 리소스에 접근하는 대상을 말하며 주로 아이디로 사용한다.Credential은 리소스에 접근하는 대상의 비밀번호로 사용한다.Spring Security 내부에는 여러 개의 필터가 필터 체이닝(Filter Chaining) 구조로
request를 처리한다.
필터의 핵심적인 동작은
AuthenticationManager를 통해 인증을 의미하는Authentication객체로 작업을 하게 된다.
AuthenticationManager가 가지는 인증 처리 메서드는 파라미터와 리턴 타입 모두 Authentication 객체이다.UsernamePasswordAuthenticationToken이며, 이는 Spring Security 필터의 주요 역할이 인증 관련 정보를 토큰이라는 객체로 만들어서 전달한다는 의미를 가진다.아래 Spring Security 동작 과정을 살펴보자.

1. 사용자가 로그인에 필요한 아이디, 비밀번호 등을 통해 로그인을 요청한다.
2. AuthenticationFilter가 로그인 정보를 인터셉트한다.
UsernamePasswordAuthenticationToken(Authentication) 객체를 생성한다.Authentication 객체는 인증 전의 객체이며 AuthenticationManager로 전달된다.3. AuthenticationManager 인터페이스를 거쳐서 AuthenticationProvider에게 Authentication 형태의 정보를 전달한다.
AuthenticationProvider들을 조회하면서 인증을 요구한다.4. AuthenticationProvider는 UserDetailsService를 통해 입력 받은 정보를 데이터베이스에서 조회한다.
supports() 메서드로 실행 가능한지 먼저 확인을 한다.authenticate() 메서드로 DB 사용자 정보와 로그인 정보를 비교한다.UserDetailsService의 loadUserByUsername() 메서드로 가져온다.Authentication 객체를 반환한다.5. AuthenticationManager는 Authentication 객체를 AuthenticationFilter로 전달한다.
6. AuthenticationFilter는 전달 받은 Authentication 객체를 LoginSuccessHandler로 전달한다.
Authentication 객체는 SecurityContextHolder에 담기게 된다.7. 인증이 성공적으로 완료되면 AuthenticationSuccessHandle을 실행하고, 그렇지 않으면 AuthenticationFailureHandle을 실행한다.
SecurityContextHolder.MODE_INHERITABLETHREADLOCAL 방식과 SecurityContextHolder.MODE_THREADLOCAL 방식을 제공한다.public interface SecurityContext extends Serializable {
Authentication getAuthentication();
void setAuthentication(Authentication authentication);
}
Authentication을 보관하는 역할을 한다.SecurityContext를 통해 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 동작 과정 그림을 보면 이해가 될 것이다.
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 { ... }
UsernamePasswordAuthenticationToken은 Authentication을 implements한 AbstractAuthenticationToken의 하위 클래스이다.Principal, 사용자 비밀번호를 의미하는 Credential이 있다.UsernamePasswordAuthenticationToken의 첫 번째 생성자는 인증 전의 객체를 생성하고, 두 번째 생성자는 인증 후의 객체를 생성한다.public interface AuthenticationProvider {
Authentication authenticate(Authentication authentication) throws AuthenticationException;
boolean supports(Class<?> authentication);
}
AuthenticationProvider에서는 실제 인증에 대한 부분을 처리한다.AuthenticationManager로부터 전달 받은 인증 전의 Authentication 객체를 받아서 인증이 완료된 Authentication 객체를 반환한다.AuthenticationProvider 인터페이스를 구현해서 개발에 필요한 AuthenticationProvider를 작성하고, AuthenticationManager에 등록하면 된다.Spring Security의 핵심 역할은
AuthenticationManager에서 이루어진다.
public interface AuthenticationManager {
Authentication authenticate(Authentication authentication) throws AuthenticationException;
}
AuthenticationManager를 통해 처리한다.AuthenticationManager에 등록된 AuthenticationProvider에 의해 처리된다.UsernamePasswordAuthenticationToken의 두 번째 생성자를 통해 인증이 성공한 객체를 생성한다.SecurityContext에 저장된다.AuthenticationException이 발생한다.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;
}
}
ProviderManager는 AuthenticationManager를 implements했다.AuthenticationProvider를 List로 가지고 있다.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를 등록할 수 있다.
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인터페이스는 주로 개발자가 직접 개발한CustomUserDetails에implements하여 사용한다.
AuthenticationProvider에서AuthenticationManager가 어떻게 동작해야 하는지를 결정한다면, 실제 인증은UserDetailsService에서 이루어진다.
public interface UserDetailsService {
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}
UserDetailsService 인터페이스는 UserDetails 객체를 반환하는 단 하나의 메서드, loadUserByUsername()을 가지고 있다.UserDetailsService를 구현한 클래스 내부에 UserRepository를 주입 받아서 DB와 연결하여 처리한다.public interface GrantedAuthority extends Serializable {
String getAuthority();
}
GrantedAuthority는 현재 사용자(principal)가 가지고 있는 권한을 말한다.ROLE_USER, ROLE_ADMIN과 같이 접두사로 ROLE_이 붙는다.GrantedAuthority 객체는 UserDetailsService에 의해 불릴 수 있고, 특정 자원에 대한 권한이 있는지를 검사하는 역할을 한다.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는 비밀번호의 단방향 암호화를 지원하는 인터페이스이다.PasswordEncoder 구현체를 제공하고 있다.BCryptPasswordEncoder이다.