spring security 처음 시작하기 - (1/n)

박도영·2022년 12월 13일
0

스프링 시큐리티란 ?

이론적인 부분입니다. 실제 사용방법은 따로 작성예정입니다...
추가예정 : authorization, OAuth2

아키텍처

  1. 클라이언트의 요청이 들어오면 HttpServletRequest, HttpServletResponse 생성
  2. FilterChain 을 탄다
// 필터체인 사용
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
		// your codes ...
	chain.doFilter(req, res);
}
  1. DelegatingFilterProxy 서블릿 컨테이너와 ApplicationContext를 연결하는 역할
    서블릿 컨테이너의 맞추면서 스프링 빈의 작업을 대표함
  2. FilterChainProxy : 그림에서 <?> 부분. 현재 요청에 대해 어떤 SecurityFilterChain을 사용할 것인지 결정함
  3. SecurityFilterChain : 드디어... 여기서부터 스프링 시큐리티 필터 체인 (오래걸렸다...)
  4. 시큐리티 필터들
    (어떤 필터가 어떤 역할을 하는지 알아두면 시큐리티를 정복하는 것 아닐까...?)

자동설정

스프링 시큐리티의 디폴트 설정.
덕분에 처음 시큐리티를 사용했을때 상당히 당황했었다...

  • springSecurityFilterChain 서블릿 필터를 생성 후 필터에 등록
  • UserDetailsService 빈 생성 후 유저네임user와 랜덤 비밀번호 생성
  • 디폴트 로그인 페이지 생성
  • CSRF 공격 방지
  • 등등 공식문서 참고

인증

스프링 시큐리티는 크게 Authentication(인증)과 Authorization(인가)로 나눌 수 있다.
인증은 내가 누구인지 식별하는 것, 인가는 내가 권한이 있는지를 확인하는 것이다.

SecurityContextHolder

인증의 핵심.
유저 정보를 담고있는 Authentication을 저장한다.
시큐리티는 SecurityContextHolder가 채워져 있다면 인증된 유저라고 판단한다.

public void securityContextHolderExample(){
        // 인증을 하는 가장 간단한 방법 : 시큐리티 컨텍스트 홀더에 authentication을 넣어준다
        SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
        Authentication authentication =
                new TestingAuthenticationToken("username", "password", "ROLE_USER");
        securityContext.setAuthentication(authentication);

        SecurityContextHolder.setContext(securityContext);
        
        // 정보 꺼내기 
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication getAuthentication = context.getAuthentication();
        String username = authentication.getName();
        Object principal = authentication.getPrincipal();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    }

Authentication

두 가지 목적으로 사용됨
1. AuthenticationManager에 입력으로서 유저가 자격을 가졌는지 확인
2. 현재 인증된 유저 정보 확인

  • principal : 유저 식별. username/password 방식에서는 UserDetails의 인스턴스
  • credentials : password
  • authorities : GrantedAuthority의 인스턴스. role이라고 생각하면 됨

AuthenticationManager

인증을 어떻게 실행할 것인지를 정의하는 API
시큐리티의 필터 인스턴스에서 사용 (AbstractAuthenticationProcessingFilter)
주로 ProviderManager 구현체 사용

ProviderManager

가장 많이 사용되는 AuthenticationManager 구현체

AuthenticationProvider

인증의 한 섹션. 특정한 인증을 실행한다.
예시 :

  • JwtAuthenticationProvider는 Jwt token 인증을 담당
  • DaoAuthenticationProvider는 username/password 기반 인증을 담당

AbstractAuthenticationProcessingFilter

시큐리티필터 체인에서 유저 인증을 담당하는 필터.
AuthenticationEntryPoint를 사용해서 자격증명을 요청할 수 있음.


참고자료 : 스프링 시큐리티 공식문서

profile
좋은 개발자란?

0개의 댓글