TIL

[TIL] 20240125 Spring security 기본

yjyj0101 2024. 1. 25. 21:26

1. spring security framework

스프링 시큐리티는 인증 (Authentication) ,권한(Authorize) 부여 및 보호 기능을 제공하는 프레임워크

Filter을 기반으로 동작, Bean으로 설정가능

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

인증방식 : credential(username, password를 이용), principal - credential 패턴

출처 : https://velog.io/@hope0206/Spring-Security-%EA%B5%AC%EC%A1%B0-%ED%9D%90%EB%A6%84-%EA%B7%B8%EB%A6%AC%EA%B3%A0-%EC%97%AD%ED%95%A0-%EC%95%8C%EC%95%84%EB%B3%B4%EA%B8%B0

 

 

2. 주요모듈

  • SecurityContextHolder, SecurityContext, Authentication 

SecurityContext에 인증이 완료된 user authenication저장, SecurityContextHolder로 접근

 

  • UsernamePasswordAuthenticationToken

Autentication을 구현한 AbstractAuthenticationToken의 하위의 하위클래스

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

public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
		super(null);
		this.principal = principal;
		this.credentials = credentials;
		setAuthenticated(false);
}
 
// 인증 완료 후의 객체 생성
public UsernamePasswordAuthenticationToken(Object principal, Object credentials,
			Collection<? extends GrantedAuthority> authorities) {
		super(authorities);
		this.principal = principal;
		this.credentials = credentials;
		super.setAuthenticated(true); // must use super, as we override
}
  • AuthenticationManager

AuthenticationManager에 등록된 AuthenticationProvider에 의해서 인증처리, 인증 후에 SecurityContext에 저장

  • UserDetailsService

UserDetails 객체를 반환하는 하나의 메서드만 있음, UserRepository를 주입받아 DB와 연결하여 처리

  • UserDetails

Authentication 객체를 구현한 UsernamePasswordAuthenticationToken을 생성하기 위해 사용함

  • GrantedAuthority

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

UserDetailsService에 의해 불러옴