02.17 Spring Security (1)
2023. 2. 17. 09:41ㆍ개발일지
Spring Security
- 스프링 서버에 필요한 인증 및 인가를 위해 많은 기능을 제공해 줌으로써 개발의 수고를 덜어 줍니다. 마치 '스프링' 프레임워크가 웹 서버 구현에 편의를 제공해 주는 것과 같습니다.
Spring Security 와 Filter
- Spring Security는 요청이 들어오면 Servlet FilterChain을 자동으로 구성한 후 거치게 합니다. FilterChain은 여러 Filter를 chain 형태로 묶어놓은 것을 의미합니다. 여기서 Filter란, 톰캣과 같은 웹 컨테이너에서 관리되는 서블릿의 기술입니다. Filter는 Client 요청이 전달되기 전후의 URL 패턴에 맞는 모든 요청에 필터링 해줍니다.
SecurityFilterChain
- Spring의 보안 Filter를 결정하는데 사용되는 Filter
- session, jwt 등의 인증방식들을 사용하는데에 필요한 설정을 완전히 분리할 수 있는 환경을 제공합니다.
AbstractAuthenticationProcessingFilter
- 사용자의 credential을 인증하기 위한 베이스 Filter
UsernamePasswordAuthenticationFilter
- UsernamePasswordAuthenticationFilter는 AbstractAuthenticationProcessingFilter를 상속한 Filter입니다.
- 기본적으로 아래와 같은 Form Login 기반을 사용할 때 username과 password 확인하여 인증합니다.
- Form Login 기반은 인증이 필요한 URL 요청이 들어왔을 때 인증이 되지 않았다면 로그인페이지를 반환하는 형태입니다.
SecurityContextHolder
- SecurityContextHolder에는 스프링 시큐리티로 인증을 한 사용자의 상세 정보를 저장합니다.
- SecurityContextHolder로 접근할 수 있으며 Authentication 객체를 가지고 있습니다.
// 예시코드
SecurityContext context = SecurityContextHolder.createEmptyContext();
Authentication authentication = new UsernamePasswordAuthenticationToken(principal, credentials, authorities);
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
Authentication
- 현재 인증된 사용자를 나타내며 SecurityContext에서 가져올 수 있습니다.
- principal : 사용자를 식별합니다. Username/Password 방식으로 인증할 때 보통 UserDetails 인스턴스입니다.
- credentials : 주로 비밀번호, 대부분 사용자 인증에 사용하고 다음 비웁니다.
- authorities : 사용자에게 부여한 권한을 GrantedAuthority로 추상화하여 사용합니다.
<UserDetails>
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
UserRoleEnum role = user.getRole();
String authority = role.getAuthority();
System.out.println("authority = " + authority);
SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authority);
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(simpleGrantedAuthority);
return authorities;
}
Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
UsernamePasswordAuthentication Token는 Authentication을 implements한 AbstractAuthenticationToken의 하위 클래스로, 인증객체를 만드는데 사용됩니다.
UserDetailsService
- username / password 인증방식을 사용할 때 사용자를 조회하고 검증한 후 UserDetails를 반환합니다. Custom하여 Bean으로 등록 후 사용 가능합니다.
UserDetails
- 검증된 UserDetails는 UsernamePasswordAuthenticationToken 타입의 Authentication를 만들 때 사용되며 해당 인증객체는 SecurityContextHolder에 세팅합니다. (Custom하여 사용가능합니다.)
'개발일지' 카테고리의 다른 글
02.18 OAuth2 (0) | 2023.02.18 |
---|---|
02.17 Spring Security (2) (0) | 2023.02.17 |
02.16 연관관계 (0) | 2023.02.16 |
02.13 @Valid와 @Validated의 차이점 (0) | 2023.02.13 |
02.12 DI / IoC / Bean (0) | 2023.02.12 |