새소식

TIL

[TIL] 230604 <Spring> Spring Security 동작원리

  • -

 

인증과 접근 제어를 위해 세부적인 맞춤 구성이 가능한 강력한 프레임워크
→ 스프링 애플리케이션에 보안을 적용하는 과정을 크게 간소화하는 프레임워크

 

Spring Security의 인증 프로세스

각 구성 요소는 인터페이스로 이루어져있음
 시큐리티의 기본 기능은 내부적으로 인터페이스를 구현한 각 구현체 클래스에 이미 구현되어 있다!

따라서 우리는 모든 것을 구현하지 않아도 되며, 필요한 구성 요소만 재정의하고 구현(맞춤 구성)하면 됨!

 

UserDetailsService (사용자 관리)

AuthenticationProviderUserDetailsService에 사용자 관리에 대한 책임을 위임

> 관련 인터페이스

  • UserDetailsService: 인증을 위해 사용자를 찾음
    • UserDetails: 사용자를 기술함
    • GrantedAuthority: 사용자가 실행할 수 있는 작업(권한)을 정의 (읽기, 쓰기, 삭제 권한 등)
    • UserDetailsManager: UserDetailsService에서 확장된 형태. 사용자의 생성, 수정, 삭제 및 암호 수정 등의 작업을 지원.
      ㄴ UserDetailsService으로 제공되는 것보다 세부 작업을 원한다면 UserDetailsManager를 이용!

 

 

PasswordEncoder (암호 처리)

AuthenticationProviderPasswordEncoder에 암호 검증에 대한 책임을 위임

> 관련 인터페이스

  • PasswordEncoder: 암호가 유효한지 확인합니다.
    • NoOpPasswordEncoder: 인코딩하지 않음. 실제 시나리오에는 절대 쓰지 말아야 ! (NoOp는 No Operation을 의미)
    • StandardPasswordEncoder: SHA-256을 이용해 암호를 해시. 강도가 약한 해싱 알고리즘을 사용하기 때문에 사용하지 않는 것이 좋음.
    • Pbkdf2PasswordEncoder: PBKDF2를 이용
    • BCryptPasswordEncoder: bcrypt 강력 해싱 함수로 암호를 인코딩
    • SCryptPasswordEncoder: scrypt 해싱 함수로 암호를 인코딩

              ㄴ 주로 BCryptPasswordEncoderSCryptPasswordEncoder를 많이 사용하며, 함께 사용하기도 함!

   
   키 생성기

  • BytesKeyGenerator: 특정 길이의 바이트 만큼의 키를 생성
  • StringKeyGenerator: 인코딩된 문자열을 키로 생성

 

 

AuthenticationProvider,  SecurityContext (인증 구현)

AuthenticationProvider로 인증이 처리되면 인증 정보가 담긴 Authentication 객체를 SecurityContext에 저장함
→ 그러면 Controller에서 SecurityContext의 인증 정보를 이용 가능

 

AuthenticationProvider 인터페이스

public interface Authenticationprovider {
	Authentication authenticate(Authentication authentication) throws AuthenticationException;
	boolean supports(Class<?> authentication);
}
  • AuthenticationProvider: 인증 로직을 처리.
    ㄴ 사용자 관리 책임은 UserDetailsService에 위임하고, PasswordEncoder에 암호 검증 책임을 위임.
  • Authentication: 인증 요청 이벤트를 나타냄. 접근을 요청한 엔티티의 세부 정보를 담음

 

 

▼ 메소드

  • authenticate(): 인증 로직을 정의하고 처리하는 메소드 (인증에 성공한 Authentication을 리턴)
    • 인증이 실패하면 AuthenticationException을 던지도록 함
    • 현재 AuthenticationProvider 구현에서 지원되지 않는 인증 객체를 받으면 null을 리턴하도록 함
      (여러 Authentication 형식을 사용한 경우)
    • 완전히 인증된 객체를 나타내는 Authentication 인스턴스를 리턴하도록 함
  • supports(): 현재 AuthenticationProvider가 해당 Authentication을 지원하는지 확인
    • 현재 AuthenticationProviderAuthentication 객체로 제공된 형식을 지원하면 true를 반환

 

SecurityContext 인터페이스
ㄴ 특정한 보안 전략을 구현하고자 할 때 재정의

public interface SecurityContext extends Serializable {
	Authentication getAuthentication();
	void setAuthentication(Authentication authentication);
}
  • SecurityContext: 인증된 엔티티 정보가 담긴 Authentication 객체를 저장하고 유지.
    AuthenticationManager는 인증 프로세스를 성공적으로 완료한 후 Authentication 인스턴스를 저장하는데 이것을 SecurityContext가 저장함
    • SecurityContextHolder: SecurityContext를 관리. controller에서 아래처럼 context를 가져올 수 있음
@GetMapping("/helLo")
public String hello() {
	SecurityContext context = SecurityContextHolder.getContext();
	Authentication authentication = context.getAuthentication();

	return "HelLo, "+ authentication.getName() + "!";
}


@GetMapping("/helLo")
// 스프링 부트가 현재 Authentication을 매개 변수로 주입하였음.
public String hello(Authentication authentication) {
	return "HelLo, "+ authentication.getName() + "!";
}
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.