👉 'Spring Security' 프레임워크는 Spring 서버에 필요한 인증 및 인가를 위해 많은 기능을 제공해 줌으로써 개발의 수고를 덜어 줍니다.
- 'Spring Security' 프레임워크 추가
implementation 'org.springframework.boot:spring-boot-starter-security'
🔥 CSRF란?
- CSRF(사이트 간 요청 위조, Cross-site request forgery)
- 공격자가 인증된 브라우저에 저장된 쿠키의 세션 정보를 활용하여 웹 서버에 사용자가 의도하지 않은 요청을 전달하는 것입니다.
- CSRF 설정이 되어있는 경우 html 에서 CSRF 토큰 값을 넘겨주어야 요청을 수신 가능합니다.
- 쿠키 기반의 취약점을 이용한 공격 이기 때문에 REST 방식의 API 에서는 disable 가능합니다.
- POST 요청마다 처리해 주는 대신 CSRF protection 을 disable 하겠습니다.
http.csrf((csrf) -> csrf.disable());
Spring Security 이해하기

Spring Security - Filter Chain
- Spring에서 모든 호출은 DispatcherServlet을 통과하게 되고 이후에 각 요청을 담당하는 Controller 로 분배됩니다.
- 이 때, 각 요청에 대해서 공통적으로 처리해야할 필요가 있을 때 DispatcherServlet 이전에 단계가 필요하며 이것이 Filter 입니다.
- Form Login 기반 인증은 인증이 필요한 URL 요청이 들어왔을 때 인증이 되지 않았다면 로그인 페이지를 반환하는 형태입니다.

UsernamePasswordAuthenticationFilter

- UsernamePasswordAuthenticationFilter는 Spring Security의 필터인 AbstractAuthenticationProcessingFilter를 상속한 Filter입니다.
- 기본적으로 Form Login 기반을 사용할 때 username 과 password 확인하여 인증합니다.
- 인증 과정
- 사용자가 username과 password를 제출하면 UsernamePasswordAuthenticationFilter는 인증된 사용자의 정보가 담기는 인증 객체인 Authentication의 종류 중 하나인 UsernamePasswordAuthenticationToken을 만들어 AuthenticationManager에게 넘겨 인증을 시도합니다.
- 실패하면 SecurityContextHolder를 비웁니다.
- 성공하면 SecurityContextHolder에 Authentication를 세팅합니다.
SecurityContextHolder

- SecurityContext는 인증이 완료된 사용자의 상세 정보(Authentication)를 저장합니다.
- SecurityContext는 SecurityContextHolder 로 접근할 수 있습니다.
Authentication

- 현재 인증된 사용자를 나타내며 SecurityContext에서 가져올 수 있습니다.
- principal : 사용자를 식별합니다.
- Username/Password 방식으로 인증할 때 일반적으로 UserDetails 인스턴스입니다.
- credentials : 주로 비밀번호, 대부분 사용자 인증에 사용한 후 비웁니다.
- authorities : 사용자에게 부여한 권한을 GrantedAuthority로 추상화하여 사용합니다.
Spring Security : 로그인
로그인처리 과정
