
✅ 스프링 시큐리티란?
인증Authentication 인가Authorization 에 대한 처리를 위임하는 별도의 프레임 워크이다.
Spring Security 의 인증 인가는 대부분을 Filter 의 흐름에 따라 처리한다.
Filter는 Dispatcher Servlet 이전에 적용 되므로 가장 먼저 URL 요청을 받는다.
✅스프링 시큐리티의 동작 과정

- 클라이언트가 DispatcherServlet 에 도달하기 전에 Filter에서 요청을 가로채 인증과 인가 에 대한 처리를 해준다.

- 사용자가 로그인 정보 id password 를 로그인 인증 Authentication 요청
- AuthenticationFilter 가 정보를 가로채 UsernamePasswordAuthentication Token 을 생성하여 (Authentication 객체) AuthenticationManager 에게 Authentication 전달
- AuthenticationManager 인터페이스를 거쳐 Autehntication Provider 에게 정보 전달, 등록된 AuthenticationProvider 를 조회하여 인증 요구 한다.
- AutenticationProvider는 UserDetailService 를 통해 입력받은 (3)의 사용자 정보를 DB에서 조회한다.
- .support()메소드가 실행 가능한지 체크
- authenticate() 메소드를 통해 DB에 저장된 이용자 정보와 입력한 로그인 정보 비교
- DB 이용자 정보 : UserDetailService 의 loadUserByUsername() 을 통해 불러옴
- 입력 로그인 정보 : (3)에서 받았던 Authentication 객체 UsernameAuthentication Token
- 일치하는 경우 Authentication 반환
- AuthenticationManager 는 Authentication 객체를 AutenticationFilter 로 전달
- AuthenticationFilter 는 전달 받은 Authentication 객체를 LoginSuccessHandler 로 전송 하고 SecurityContextHolder 에 담는다.
- 성공시 AuthenticationSucesshandle 실패시 AuthenticationFailureHandle 실행
🖥️ 의존성 추가시 보게될 첫 화면

서버 빌드시 password 확인이 가능하며 기본 id는 user 이다
✅ 스프링 시큐리티 특징
- Filter 기반으로 동작한다.
(MVC와 분리하여 관리 및 동작) - Bean으로 설정할 수 있다.
(어노테이션을 통한 간단한 설정이 가능) - Spring Security는 기본적으로 세션 & 쿠키 방식으로 인증한다.
- 인증관리자(Authentication Manager)와 접근 결정 관리자(Access Decision Manager)를 통해 사용자의 리소스 접근을 관리한다.
(인증 관리자는 UserNamePasswordAuthenticationFilter, 접근 관리자는 FilterSecurityInterceptor가 수행)
흐름 Client(request) -> Filter -> DispatcherServlet -> Intercepter -> Controller
✏️ 공부한 내용 Filter와 Intercepter의 차이
1. Filter
Filter는 J2EE표준 스펙 기능으로, Dispatcher Servlet에 요청이 전달되기 전/후에 url 패턴에 맞는 모든 요청에 대한 작업을 처리할 수 있는 기능을 제공합니다.
Filter는 스프링 컨테이너가 아닌 웹 컨테이너(톰캣)에 의해 관리됩니다.
- Web Application에 등록한다.
- 스프링 컨텍스트 외부에 존재하여 스프링과 무관한 자원에 대해 동작한다.
- Request, Response 객체를 직접 조작할 수 있다.
- 인코딩 처리, 보안, 로그인과 권한 검사 등의 요청에 대한 처리
[ 필터의 실행 메서드 ]
- init() - 필터 객체 초기화, 이후 요청들은 doFilter를 통해 처리된다.
- doFilter() - 전/후 처리
- url-pattern에 맞는 모든 HTTP 요청이 디스패처 서블릿으로 전달되기 전 웹 컨테이너에 의해 실행
- destroy() - 필터 객체 종료
2. Interceptor
인터셉터는 Spring이 제공하는 기술로 Dispatcher Servlet이 컨트롤러를 호출하기 전과 후에 끼어들어 스프링 컨텍스트 내부에서 Controller(Handler)에 관한 요청과 응답에 대해 처리합니다.
인터셉터는 스프링 컨테이너 내에서 동작하므로 필터를 거쳐 프런트 컨트롤러인 디스패처 서블릿이 요청을 받은 이후에 동작합니다.
- Spring의 Context에 등록한다.
- 스프링의 모든 Bean에 접근할 수 있다.
- Request, Response 객체를 직접 조작할 수 없다.
- 인터셉터 여러 개 사용할 수 있고, 로그인 체크, 권한 체크 등의 업무 처리
[ 인터셉터의 실행 메서드 ]
- preHandler() - 컨트롤러 메서드가 실행되기 전에 실행
- 전처리 작업, 요청 정보 가공
- postHanler() - 컨트롤러 메서드 실행 직후 view페이지 렌더링 되기 전
- 후처리 작업
- afterCompletion() - view페이지가 렌더링 되고 난 후
- 요청 처리 중에 사용한 리소스 반환
3. Filter와 Interceptor 차이
| 대상 | 필터(Filter) | 인터셉터(Interceptor) |
| 관리되는 컨테이너 | 웹 컨테이너 | 스프링 컨테이너 |
| Request / Response 객체 조작 가능 여부 |
O | X |
| 용도 | - 공통된 보안 및 인증/인가 관련 작업 - 모든 요청에 대한 로깅 또는 감사 - 이미지/데이터 압축 및 문자열 인코딩 - Spring과 분리되어야 하는 기능 |
- 세부적인 보안 및 인증/인가 공통 작업 - API호출에 대한 로깅 또는 감사 - Controller로 넘겨주는 데이터의 가공 |
4. 용도
필터는 스프링과 무관하게 전역적으로 처리해야 하는 작업이나 웹 애플리케이션 전반적으로 사용되는 기능을 구현하고
인터셉터는 클라이언트의 요청과 관련된 전역적으로 처리해야하는 작업이나 컨트롤러로 넘겨주기 위해 데이터 가공하는 작업
즉 필터는 스프링과 무관하게 전역으로 인증인가 관련 작업을 하는것인고 인터셉터는 Controller로 넘겨주는 데이터를 가공하거나 로깅할때 스프링 컨테이너에서 작동하는 것이다.
✅ 스프링 3.xx 버전 시큐리티 설정
@Bean 등록
기존코드와 비교를 하면 다음과 같다
- 기존코드
@Configuration
@EnableWebSecurity // Spring Security 설정 활성화
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { //adapter
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/users/**", "/settings/**").hasAuthority("admin")
.hasAnyAuthority("admin", "user")
.anyRequest().authenticated()
.and().formLogin()
.loginPage("/login")
.usernameParameter("email")
.permitAll()
.and()
.logout().permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/images/**", "/js/**", "/webjars/**");
}
}
- 수정코드
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeRequests(auth -> auth
.antMatchers("/login").permitAll()
.antMatchers("/images/**", "/js/**", "/webjars/**").permitAll()
.antMatchers("/users/**", "/settings/**").hasAuthority("admin")
.antMatchers("/**").hasAnyAuthority("admin", "user")
.anyRequest().authenticated()
)
.formLogin(form -> form
.loginPage("/login")
.usernameParameter("email")
.permitAll()
)
.logout(logout -> logout.permitAll());
return http.build();
}
}
✏️ 공부한점
기존에 WebSecurityConfigurerAdapter를 extends 해서 configure 함수를 오버라이드 했던 방식에서 스프링 3.xx 으로 업그레이드 되면서 SecurityFilterChain을 @Bean 등록해서 사용하는 방식으로 바뀌었다.
'Back-end > Spring Security' 카테고리의 다른 글
| [Spring Security] Security + JWT 설정 (JwtFilter편) (0) | 2025.05.27 |
|---|---|
| [Spring Security] Security + JWT 설정 (JwtUtil편) (1) | 2025.05.27 |