본문 바로가기
web/spring

Spring Security (1) - spring security란?

by su0a 2024. 2. 3.

1. Spring Security

인증(Authentication), 권한(Athorization)을 부여하고 보호하는 기능을 제공한다.

인증(Authentication) 접근하려는 유저가 누구인지 확인하는 절차 (로그인)
인가(Authorization) 인증된 사용자가 요청된 자원에 접근 가능한지 확인하는 절차 (사용자가 관리자 페이지에 접근하는 경우)

 

 

2. 인증, 인가를 위해 사용하는 인증방식

사용자명과 비밀번호로 인증하는 Credential 기반의 인증방식을 사용한다.

사용자명(username) principal (접근주체 - 보호받는 리소스에 접근하는 대상)
비밀번호(password) credential (비밀번호 - 리소스에 접근하는 대상의 비밀번호)

 

 

3. 스프링 시큐리티 인증 작동방식

 

1) Http Request 수신

  • 사용자가 로그인 정보를 입력하고 인증을 요청한다.

2) UsernamePasswordAuthenticationToken 객체 생성

  • AuthenticationFilter가 인증 요청을 가로채서 사용자가 보낸 사용자명(username)과 비밀번호(password)로 
  • UsernamePasswordAuthenticationToken 객체를 생성한다.

3) AuthenticationFilter는 UsernamePasswordAuthenticationToken을 AthenticationManager에게 위임

  • AuthenticationManager의 구현체인 ProviderManager에게 인증을 위한 객체(UsernamePasswordAuthenticationToken)를 전달한다.

4) AuthenticationProvider에게 Authentication 객체(UsernamePasswordAuthenticationToken)를 전달

  • 실제 인증을 할 AuthenticationProvider에게 Authentication 객체를 보내고 인증을 요구한다.

5) AuthenticationProvider은 UserDetailsService를 통해 사용자 정보 조회

  • UserDetailsService를 통해 입력받은 사용자명(username)에 대한 사용자 정보를 DB 내의 User 테이블 에서 조회한다.

6) UserDetails를 이용해 DB에서 조회한 사용자 정보를 담은 객체생성

  • User에 입력받은 username에 대한 정보가 있는 경우 DB에서 찾아낸 정보를 담은 UserDetails 객체를 만든다.

7) UserDetailsService는 AuthenticationProvider에게 UserDetails 객체를 전달

  • AuthenticationProvider은 전달받은 UserDetails와 로그인을 요청한 사용자 정보와 비교한다.

8) 인증이 되었을 경우 Authentication객체 반환, 인증이 되지 않았을 경우 AuthenticationException 반환

  • 인증이 완료되면 사용자 정보를 포한한 Authentication객체를 AuthenticationManager로 반환한다.

9) AuthenticationManager은 Authentication객체(UsernameAuthenticationToken)를 AuthenticationFilter에게 반환

 

10) AuthenticationFilter 은 전달받은 UsernameAuthentication을 SecurityContextHolder 에 저장 

  • 인증된 경우 AuthenticationSuccessHandler 실행, 실패 시 AuthenticationFailureHandler 실행한다.