Spring Security
- Spring 기반의 애플리케이션의 보안(인증과 인가)를 담당하는 프레임워크이다.
- 보안과 관련해서 체계적으로 많은 옵션들을 제공해준다.
→ 보안 처리를 더 쉽고 요구사항에 맞게 개발할 수 있게 도와준다.
사전 개념
-
필터
- 필터는 체인처럼 엮어있기 때문에
필터 체인
이라고도 불리는데, 모든 request는 이 필터 체인을 반드시 걸쳐야 한다.
- spring security 는 필터 기반으로 동작하기 때문에 spring MVC 와 분리되어 관리 및 동작한다.
- 즉, Interceptor, AOP 와 따로 동작한다.

-
Security 용어
- 접근 주체 (Principla) : 보호된 대상에 접근하는 사용자
- 인증 (Authentication) :
증명
, 어떤 개체(사용자 또는 장치)의 신원을 확인하는 과정
ex. ID/PW 로그인 방식, SMS 인증, OAuth 2, Token 방식
- 인가 (Authorization) :
허락
, 어떤 개체가 어떤 리소스에 접근할 수 있는지 도는 어떤 동작을 수행할 수 있는지를 검증하는 것
ex. Role, Authority 기반 인가 처리
-
세션 - 쿠키
- spring security의 기본 방식은 세션-쿠키 방식으로 인증한다.
- 유저가 로그인을 시도 (http request)
- AuthenticationFilter 에서부터 user DB까지 타고 들어감
- DB에 있는 유저라면 UserDetails로 꺼내서 유저의 session 생성
- spring security의 인메모리 세션저장소인 SecurityContextHolder 에 저장
- 유저에게 session ID와 함께 응답을 내려줌
- 이후 요청에서는 요청쿠키에서 JSESSIONID를 까봐서 검증 후 유효하면 Authentication를 쥐어준다.
Spring Security 내부 구조

// 객체 코드
SecurityContext context = SecurityContextHolder.getContext(); // Security Context
Authentication authentication = context.getAuthentication(); // authentication
authentication.getPrincipal();
authentication.getAuthorities();
authentication.getCredentials();
authentication.getDetails();
authentication.isAuthenticated();
- SecurityContextHolder
SecurityContextHolder는 SecurityContext를 제공하는 static 메소드(getContext)를 지원한다.
- SecurityContext
SecurityContext 는 접근 주체와 인증에 대한 정보를 담고 있는 Context 이다.
즉, Authentication 을 담고 있습니다.
- Authentication
Principal과 GrantAuthority를 제공합니다.
인증이 이루어 지면 해당 Athentication이 저장됩니다
- Principal
유저에 해당하는 정보입니다.
대부분의 경우 Principal로 UserDetails를 반환합니다
- Authorities → GrantedAuthority
ROLE_ADMIN, ROLE_USER 등 Principal이 가지고 있는 권한을 나타냅니다.
prefix로 (ROLE__)이 붙습니다.
인증 이후에 인가를 할 때 사용합니다. 권한은 여러개일수 있기 때문에 Collection<(GrantedAuthority)>형태로 제공합니다.
ex) ROLE_DEVELOPER, ROLE_ADMIN
Spring Security 기본 로그인 인증 처리 과정

로그인 인증 처리 순서 → http.formLogin() 을 설정
- 로그인 요청이 들어오면 AuthenticationFilter(UsernamePasswordAuthenticationFilter)를 거친다.