티스토리 뷰

Project 댕린이집

[Spring Security] 기본 개념

xoo | 수진 2024. 1. 25. 22:33

1️⃣ Spring Security 란?

Web 기반 Application에 보안적인 제한을 추가하기 위해 사용하는 Security Framework 중에 하나입니다. Spring Security의 주된 목표는 rest api endpoint, mvc url, 정적 리소스와 같은 리소스들에 접근하려는 요청의 인증을 책임지는 것 입니다. Spring Security는 Spring 생태계와 호환성이 높고 커스텀이 매우 쉽습니다.

⇒ 스프링 생태계에서 인증과 인가라는 개념을 최대한 쉽고 유연하게 구현할 수 있도록 만들어진 프레임워크. Spring을 사용한다면 사실상 최선의 Security Framework 입니다 !

 

 

인증(Authentication)

사용자가 누구인지 확인하는 절차. ( ex. 로그인 )

단순히 로그인 하면 되지! 라는 생각으로는 해결되지 않습니다. 로그인을 한번 하고 난 뒤, 서비스를 이용하는 중에도 계속해서 인증이 이루어져야 하기 때문이죠.

 

인가 (Authorization)

인가는 인증 이후에 리소스에 대한 권한 통제를 의미합니다. 클라이언트가 요청한 작업이 허가된 작업인지 확인하는 절차 입니다.

 


 

2️⃣ 인증 방식

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

 

이중 Spring Security는 credential 기반의 인증을 취합니다.

  • principal: 아이디 (username)
  • credential: 비밀번호 (password)

특정 자원에 대한 접근을 제어하기 위해서는 권한을 가지게 됩니다.

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

 


 

3️⃣ Spring Security의 특징

  • Filter를 기반으로 동작.
    • Spring MVC와 분리되어 관리하고 동작할 수 있습니다.
  • Bean으로 설정할 수 있습니다.
    • Spring Security 3.2부터는 XML설정을 하지 않아도 됩니다.

 


 

3️⃣ Spring Security Architecture

SecurityContextHolderSecurityContextAuthenticationPrincipal & GrantAuthority

 

  • SecurityContextHolder : SecurityContext를 갖고 있는 객체. SecurityContext를 제공하는 static 메소드 (getContext) 를 지원합니다.
  • SecurityContext : 접근 주체와 인증에 대한 정보를 담고 있는 Context 입니다. 즉, Authentication을 담고 있습니다.
  • Authentication : Principal과 GrantAuthority를 제공합니다. 인증이 이루어 지면 해당 Authentication이 저장됩니다.
  • Principal : 유저에 해당하는 정보. 인증 관련 실제 사용자와 관련된 정보를 담고있는 객체 입니다. 대부분의 경우 Principal로 UserDetails (인터페이스) 를 반환합니다.
  • GrantAuthority : 인가된 권한들을 담고있는 객체.
    • ROLE_ADMIN, ROLE_USER 등 Principal이 가지고 있는 권한을 나타냅니다.
    • prefix로 ‘ROLE_’이 붙습니다.
    • 인증 이후에 인가를 할 때 사용합니다.
    • 권한은 여러 개 일 수 있기 때문에 Collection<GrantedAuthority> 형태로 제공합니다.

 

[ 그림으로 보는 내부구조 ]

 

 

[ 코드로 보는 내부구조 ]

SecurityContext context = SecurityContextHolder.getContext();   // Security Context
Authentication authentication = context.getAuthentication();   // authentication
authentication.getPrincipal();
authentication.getAuthorities();
authentication.getCredentials();
authentication.getDetails();
authentication.isAuthenticated();

 

 


 

4️⃣ Spring Security의 흐름

1. Http Request 수신 

-> 사용자가 로그인 정보와 함께 인증 요청을 한다.

 

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

-> AuthenticationFilter가 요청을 가로채고, 가로챈 정보를 통해 UsernamePasswordAuthenticationToken의 인증용 객체를 생성한다.

 

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

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

 

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

-> AutenticationManger는 등록된 AuthenticationProvider들을 조회하며 인증을 요구한다.

 

5. UserDetailsService의 요구

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

 

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

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

 

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

-> AuthenticaitonProvider들은 UserDetails를 넘겨받고 사용자 정보를 비교한다.

 

8. 인증 객체 or AuthenticationException

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

 

9. 인증 끝

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

 

10. SecurityContext에 인증 객체를 설정

-> Authentication 객체를 Security Context에 저장한다.

최종적으로는 SecurityContextHolder는 세션 영역에 있는 SecurityContext에 Authentication 객체를 저장한다. 사용자 정보를 저장한다는 것은 스프링 시큐리티가 전통적인 세선-쿠키 기반의 인증 방식을 사용한다는 것을 의미한다.

 

 

참고 https://dev-coco.tistory.com/174#head3

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함