Spring Security 개념

minchan·2024년 8월 17일

Spring Security

목록 보기
4/5

1. Spring Security 란?

Spring Security는 인증 (Authentication) ,권한(Authorize) 부여 및 보호 기능을 제공하는 프레임워크

Spring Security를 사용함으로써 짜여진 내부 로직을 통해 인증, 권한 확인에 필요한 기능과 옵션들을 제공

1.1 인증/인가

보통 인증 절차를 거친 후 인가 절차를 진행

  • 인증: 해당 사용자가 본인이 맞는지를 확인하는 절차
  • 인가: 인증된 사용자가 요청된 자원에 접근 가능한가를 결정하는 절차

💡 인증 방식

  • credential 방식 : username, password를 이용하는 방식
  • 이중 인증(twofactor 인증) : 사용자가 입력한 개인 정보를 인증 후, 다른 인증 체계(예: 물리적인 카드)를 이용하여 두가지의 조합으로 인증하는 방식
  • 하드웨어 인증: 자동차 키와 같은 방식

Spring Security는 Credential 방식을 사용

  • principal(아이디), credential(비밀번호)

특정 자원에 대한 접근을 제어하기 위해서는 권한을 가져야 함

  • 특정 권한을 얻기 위해서는 유저는 인증정보(Authentication)가 필요하고 관리자는 해당 정보를 참고해 권한을 인가(Authorization)함

보편적으로 username - password 패턴의 인증방식을 거치기 때문에 스프링 시큐리티는 principal - credential 패턴을 가지게 됨

1.2 Spring Security의 특징

  1. Filter를 기반으로 동작 : Spring MVC와 분리되어 관리하고 동작 가능
  2. Bean으로 설정할 수 있음

2. Spring Security 구조 및 흐름

  1. Http Request 수신 

    사용자가 로그인 정보와 함께 인증 요청

  2. 유저 자격을 기반으로 인증토큰 생성 

    AuthenticationFilter요청을 가로채고, 가로챈 정보를 통해 UsernamePasswordAuthenticationToken인증용 객체를 생성

  3. FIlter를 통해 AuthenticationToken을 AuthenticationManager로 위임

    AuthenticationManager의 구현체인 ProviderManager에게 생성한 UsernamePasswordToken 객체를 전달

  4. AuthenticationProvider의 목록으로 인증을 시도

    AuthenticationManger는 등록된 AuthenticationProvider들을 조회하며 인증을 요구

  5. UserDetailsService의 요구

    실제 데이터베이스에서 사용자 인증정보를 가져오는 UserDetailsService에 사용자 정보를 넘겨줌

  6. UserDetails를 이용해 User객체에 대한 정보 탐색

    넘겨받은 사용자 정보를 통해 데이터베이스에서 찾아낸 사용자 정보인 UserDetails 객체를 만듬

  7. User 객체의 정보들을 UserDetails가 UserDetailsService(LoginService)로 전달

    AuthenticationProvider들은 UserDetails를 넘겨받고 사용자 정보를 비교

  8. 인증 객체 or AuthenticationException

    인증이 완료가 되면 권한 등의 사용자 정보를 담은 Authentication 객체를 반환

  9. 인증 끝

    다시 최초의 AuthenticationFilter에 Authentication 객체가 반환된다.

  10. SecurityContext에 인증 객체를 설정

    Authentication 객체를 Security Context에 저장

3. Spring Security 주요 모듈

3.1 SecurityContextHolder, SecurityContext, Authentication

유저의 아이디와 패스워드 사용자 정보를 넣고 실제 가입된 사용자인지 체크한 후 인증에 성공하면 사용자의 principal과 credential정보를 Authentication안에 담음

스프링 시큐리티에서 방금 담은 Authentication을 SecurityContext에 보관

이 SecurityContext를 SecurityContextHolder에 담아 보관하게 되는 것

Authentication 클래스는 현재 접근하는 주체의 정보와 권한을 담는 인터페이스고 SecurityContext에 저장되며 SecurityContextHolder를 통해 SecurityContext에 접근하고, SecurityContext를 통해 Authentication에 접근할 수 있음

// 로그인한 사용자의 정보를 얻어오는 코드
SecurityContextHolder.getContext().getAuthentication().getPrincipal();

3.2 UsernamePasswordAuthenticationToken

이 클래스는 Authentication을 구현한 AbstractAuthenticationToken의 하위의 하위클래스로, 유저의 ID가 Principal의 역할을 하고 유저의 Password가 Credential의 역할을 함

UserPasswordAuthenticationToken의 첫번째 생성자는 인증 전에 객체를 생성하고, 두번째는 인증이 완료된 객체를 생성

3.3 AuthenticationManager

인증에 대한 부분은 이 클래스를 통해서 처리가 됨

실질적으로는 AuthenticationManager에 등록된 AuthenticationProvider에 의해서 처리가 됨

3.4 AuthenticationProvider

이 클래스는 실제 인증에 대한 부분을 처리하는 작업을 치룸

인증 전에 Authentication 객체를 받아 인증이 완료된 객체를 반환하는 역할

3.5 ProviderManager

AuthenticationManager를 구현한 ProviderManager은 AuthenticationProvider를 구성하는 목록을 가짐

3.6 UserDetailsService

이 클래스는 UserDetails 객체를 반환하는 하나의 메서드만을 가지고 있는데, 일반적으로 이를 구현한 클래스에서 UserRepository를 주입받아 DB와 연결하여 처리

3.7 UserDetails

인증에 성공하여 생성된 UserDetails클래스는 Authentication 객체를 구현UsernamePasswordAuthenticationToken을 생성하기 위해 사용

3.8 GrantedAuthority

GrantedAuthority는 현재 사용자(Pricipal)가 가지고 있는 권한을 의미하며 ROLEADMIN, ROLE_USER와 같이 ROLE* 형태로 사용

GrantedAuthority객체는 UserDetailsService에 의해 불러올 수 있고, 특정 자원에 대한 권한이 있는지 없는지를 검사해 접근 허용 여부를 결정

🔒 Spring Security 구조, 흐름 그리고 역할 알아보기 🌱

profile
chanmin

0개의 댓글