SPRING :: Security
Spring Security
Spring 기반의 애플리케이션의 보안(인증과 권한, 인가 등)을 담당하는 스프링 하위 프레임워크. Spring Security는 '인증'과 '권한'에 대한 부분을 Filter 흐름에 따라 처리하고 있다. Filter는 Dispatcher Servlet으로 가기 전에 적용되므로 가장 먼저 URL 요청을 받지만, Interceptor는 Dispatcher와 Controller사이에 위치한다는 점에서 적용 시기의 차이가 있다.
Spring Security 작동 구조
1. 사용자는 로그인을 위해 아이디와 비밀번호를 입력한다.
2. 요청이 오면 AuthenticationFilter에서 요청을 가로채고 아이디와 비밀번호를 기반으로
UserPasswordAuthenticastionToken을 발급해준다.
3. 발급된 토큰을 AuthenticationManager에게 전달한다. 본 매니저는인증을 처리할 Provider를
여러개 가진다.
4. Manager가 Provider에게 전달하여 인증 과정을 수행한다. (authenticate 메서드)
5. UserDetailsService로 조회할 아이디를 전달하여 조회한다.
6. DB에서 아이디를 조회한다.
7. 조회 결과를 반환한다.
8. 인증 처리 후 인증 결과가 담긴 토큰을 AuthenticationManager에게 반환한다.
9 .인증된 토큰을 AuthenicationFilter -> SecurityContextHolder에 전달하여 인증을 끝내고 인증 정보를
Principal 객체에 담아 보관한다.
Spring Security 주요 인증 수단
1. 아이디, 비밀번호 로그인 (Form-Based Authentication)
- 가장 기본적인 로그인 방식으로, 사용자 아이디와 비밀번호를 입력하여 인증
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. JWT 토큰 로그인
- JSON Web Token을 사용하여 사용자 인증을 처리. 서버가 토큰을 발급하면 클라이언트는 이 토큰을 통해 인증된 요청을 보냄
- starter에 없으므로 repository 사이트에서 검색
- Oauth2과 연계 사용을 위한 토큰은 [Spring Security JWT Library » 1.1.1.RELEASE] 를 사용하면 된다
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.6</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.12.6</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.12.6</version>
<scope>runtime</scope>
</dependency>
2-1. Spring Security JWT Library » 1.1.1.RELEASE
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>1.1.1.RELEASE</version>
</dependency>
3. OAuth2 로그인
- Google, Facebook 등 외부 OAuth2 제공자를 통해 로그인하는 방식
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>