Spring Security 필터 체인
1. SecurityContextPersistenceFilter
2. LogoutFilter
3. *UsernamePasswordAuthenticationFilter*
4. DefaultLoginPageGeneratingFilter
5. BasicAuthenticationFilter
6. RequestCacheAwareFilter
7. SecurityContextHolderAwareRequestFilter
8. AnonymousAuthenticationFilter
9. SessionManagementFilter
10. ExceptionTranslationFilter
11. *FilterSecurityInterceptor*
핵심 필터 두 가지에 주목하자
- UsernamePasswordAuthenticationFilter
- 폼 로그인 기반 인증을 처리하는 필터다.
- 사용자가 로그인 폼에 ID/PW를 입력해 요청을 보내면 해당 필터가 이를 가로채서 인증을 시도한다.
- 인증에 성공하면 AuthenticationSuccessHandler, 실패하면 AuthenticationFailureHandler가 호출된다.
- FilterSecurityInterceptor
- 인가(Authorization)의 핵심.
- 이미 인증된 사용자에 대해 해당 요청에 대한 권한이 있는지를 최종적으로 체크한다.
인증(Authentication) 흐름
Spring Security에서 "로그인"이 이루어지는 전체 과정은 다음과 같다:
- HTTP 요청
- 사용자가 ID와 PW를 입력하여 /login 요청을 보낸다.
- UsernamePasswordAuthenticationFilter 동작
- 해당 필터가 요청을 가로채고 인증 시도를 시작한다.
- UsernamePasswordAuthenticationToken 생성
- ID/PW가 유효하면 이 정보를 담은 Authentication 객체가 생성된다.
- AuthenticationManager에게 토큰 전달
- Spring Security는 이 토큰을 AuthenticationManager에 전달하여 인증을 위임한다.
- AuthenticationProvider 작동
- AuthenticationProvider는 내부적으로 UserDetailsService를 호출하여 DB에서 사용자 정보를 조회한다.
- DB 사용자 정보 로딩
- 조회된 사용자 정보를 UserDetails 객체로 생성하고, 입력 정보와 비교한다.
- 인증 성공
- 정보가 일치하면 인증 완료 → SecurityContextHolder에 저장되어 이후 요청에 재사용된다.
인가(Authorization) - 권한 제어
인증을 완료한 사용자라도, 모든 API나 페이지에 접근할 수 있는 건 아니다. 이때 필요한 것이 바로 인가 처리다.
Spring Security는 아래처럼 @PreAuthorize 애너테이션을 통해 메서드 단위로 권한을 제어할 수 있게 해준다
import org.springframework.security.access.prepost.PreAuthorize;
public class R_Authority {
@PreAuthorize("hasRole('USER')") // "ROLE_" 접두사는 자동으로 붙는다!
public String userProfile() {
return "User Profile";
}
@PreAuthorize("hasAnyRole('USER', 'ADMIN')") // 둘 중 하나만 있어도 접근 가능
public String commonData() {
return "Accessible by USER or ADMIN";
}
@PreAuthorize("hasAuthority('ROLE_ADMIN')") // Authority는 prefix 명시 필요
public String adminDashboard() {
return "Admin Dashboard";
}
}
'웹개발 > SpringBoot' 카테고리의 다른 글
| Spring WebFlux의 개념과 구조적 특징 (1) | 2025.05.29 |
|---|---|
| JWT(JSON Web Token) (0) | 2025.05.28 |
| Rest API (1) | 2025.05.26 |
| Response/Request &Validation (0) | 2025.05.25 |
| @Bean VS @Component (0) | 2025.05.24 |