코이팅

Spring Security란 본문

CS

Spring Security란

코이팅 2023. 1. 14. 01:44
728x90
반응형

1. Spring Security란?

[Spring Security란 ?]

Spring Security는 Spring 기반의 애플리케이션의 보안(인증, 권한, 인가 등)을 담당하는 스프링 하위 프레임워크입니다. 이 프레임워크를 사용하면 보안처리를 자체적으로 구현하지 않아도 필요한 기능을 쉽게 구현할 수있습니다. 즉, 보안과 관련해서 체계적으로 많은 옵션을 제공해주기 때문에 일일이 보안관련 로직을 작성하지 않아도 됩니다. Spring Security는 '인증'과 '권한'에 대한 부분을 Filter 흐름에 따라 처리하고 있습니다.

 

**[인증(Authentication)]

인증은 해당 사용자가 본인이 맞는지 확인하는 절차입니다.  유저가 누구인지 확인하는 것, 회원가입과 로그인을 하는 것을 말합니다.

 

**[인가(Authorization)]

인증된 사용자가 요청한 자원에 접근 가능한지를 결정하는 절차입니다. 즉, 유저에 대한 권한을 확인, 허락하는 것을 말합니다.

 

[Spring Security 특징]

  • Spring Security는 filter 기반으로 동작하기 때문에(AOP) Spring MVC와 분리되어 관리 및 동작합니다.
  • Spring Security는 세션-쿠키 방식으로 인증합니다.
  • Spring Security는 스프링의 DispatcherServlet 앞단에 Filter 형태로 위치합니다.
  • Dispatcher로 넘어가기 전에 이 Filter가 요청을 가로채서 클라이언트의 리소스 접근 권한을 확인하고, 없는 경우에는 인증 요청 화면으로 자동 리다이렉트합니다.

 

2. Spring Security 모듈

[SecurityContextHolder]

  • SecurityContextHolder는 SecurityContext를 제공하는 static 메소드(getContext)를 지원합니다.

[SecurityContext]

  • SecurityContext는 접근 주체와 인증에 대한 정보를 담고 있는 Context입니다.
  • 즉, Authentication을 담고있습니다.

[Authentication]

  • Principal과 GrantAuthority를 제공합니다.
  • 인증이 이루어지면 해당 Authentication이 SecurityContext에 저장됩니다.
  • SecurityContextHolder를 통해 SecurityContext에 접근하고, SecurityContext를 통해 Authentication에 접근할 수 있습니다.

[Principal]

  • 유저에 해당하는 정보입니다.
  • 대부분의 경우 Principal로 UserDetails를 반환합니다.

[GrantAuthority]

  • ROLEADMIN, ROLE_USER 등 Principal이 가지고 있는 권한을 나타냅니다.
  • prefix로 'ROLE'이 붙습니다.
  • 인증 이후에 인가를 할 때 사용합니다.
  • 권한은 여러개일 수 있기 때문에 Collection<(GrantedAuthority)> 형태로 제공합니다.
    ex) ROLE_DEVELOPER, ROLE_ADMIN

[UsernamePasswordAuthenticationToken]

  • Authentication을 implements한 AbstractAuthenticationToken의 하위 클래스입니다.
  • User의 ID가 Principal 역할을 하고, Password가 Credential의 역할을 합니다.
  • UsernamePasswordAuthenticationToken의 첫 번째 생성자는 인증 전의 객체를 생성하고, 두 번째 생성자는 인증이 완료된 객체를 생성합니다.

[Authentication Provider]

  • Authentication Provider에서는 실제 인증에 대한 부분을 처리합니다.
  • Authentication 객체를 받아서 인증이 완료된 객체를 반환하는 역할을 합니다.
  • Authentication Provider 인터페이스를 구현해서 Custom한 Authentication Provider을 작성하고, AuthenticationManager에 등록하면 됩니다.

[Authentiaction Manager]

  • 인증에 대한 부분은 SpringSecurity의 Authentication Manager를 통해서 처리하게 되는데, 실질적으로는 Authentication Manager에 등록된 Authentication Provider에 의해서 처리됩니다.
  • 인증이 성공하면 2번째 생성자를 이용해 인증이 성공한 객체를 생성하여 Security Context에 저장합니다.
  • 인증 상태를 유지하기 ㅜ이해 세션에 보관하고, 인증이 실패하면 AuthenticationException을 발생시킵니다.

[UserDetails]

  • 인증에 성공하여 생성된 UserDetails 객체는 Authentication 객체를 구현 UsernamePasswordAuthentication을 생성하기 위해 사용됩니다.

[UswerDetailsService]

  • UserDetailsService 인터페이스는 UserDetails 객체를 반환하는 단 하나의 메소드를 가지고 있습니다.
  • 일반적으로 이를 구현한 클래스의 내부에 UserRepository를 주입받아 DB와 연결하여 처리합니다.

[PasswordEncoding]

  • AuthenticationManagerBuilder.userDetailsService().passwordEncoder()를 통해 패스워드 암호화에 사용될 PasswordEncoder 구현체를 지정할 수 있습니다.

 

3. Spring Security Architecture

출처 : https://ayush1608.medium.com/how-does-spring-security-works-internally-14447a43ef5b

 

1) 처음에 요청이 들어오면 AuthenticationFilter(UsernamePassAuthenticationFilter)를 거칩니다.

2) 요청에 따른 UsernamePasswordAuthenticationToken을 생성합니다. (Authentication 인터페이스의 구현체입니다.)

3) UsernamePasswordAuthenticationToken을 AuthenticationManager에게 이 Token이 올바른 유저인지 물어봅니다.

4) AuthenticationManager는 1개 이상의 AuthenticationProvider를 갖고 있는데, AuthenticationProviderUsernamePasswordAuthenticationToken객체를 적절히 판단하여 인증처리를 할려고 합니다.

5) AuthenticationProvider가 우리가 직접 구현한 서비스(UserDetailsService 구현 클래스)에 해당 유저에게 인증요청을 보내 사용자 정보를 가져옵니다.

6) UserDetailsService 구현 클래스는 사용자 정보를 가져와 UserDetails를 반환합니다.

7-10) Provider는 UserDetailsService에서 반환된 UserDetails와 클라이언트가 제공한 인증정보(Token)를 대조해서 이용자가 정당한 사용권한을 가지고 있는지 확인합니다. 그리고 SecurityContext에 저장합니다.

 

728x90
반응형

'CS' 카테고리의 다른 글

시간복잡도(Time Complexity)  (0) 2023.01.15
JWT(Json Web Token)란?  (0) 2023.01.14
컴퓨터의 구성  (0) 2023.01.05
객체 지향 프로그래밍(Object-Oriented Programming, OOP)의 개념과 4가지 특징  (0) 2023.01.05
DNS란?  (0) 2022.07.27
Comments