Spring Security
Spring Security는 Spring 기반의 애플리케이션의 보안(인증과 권한, 인가 등)을 담당하는 스프링 하위 프레임워크이다. Spring Security는 '인증'과 '권한'에 대한 부분을 Filter 흐름에 따라 처리하고 있다. Filter는 Dispatcher Servlet으로 가기 전에 적용되므로 가장 먼저 URL 요청을 받지만, Interceptor는 Dispatcher와 Controller사이에 위치한다는 점에서 적용 시기의 차이가 있다. Spring Security는 보안과 관련해서 체계적으로 많은 옵션을 제공해주기 때문에 개발자 입장에서는 일일이 보안관련 로직을 작성하지 않아도 된다는 장점이 있다.
SecurityContextHolder -> SecurityContext -> Authentication -> Pricipal & GrantAuthority 순서
SecurityContextHolder
SecurityContextHolder는 보안 주체의 세부 정보를 포함하여 응용프래그램의 현재 보안 컨텍스트에 대한 세부 정보가 저장된다. SecurityContextHolder는 기본적으로 SecurityContextHolder.MODE_INHERITABLETHREADLOCAL 방법과SecurityContextHolder.MODE_THREADLOCAL 방법을 제공한다.
SecurityContext
Authentication을 보관하는 역할을 하며, SecurityContext를 통해 Authentication 객체를 꺼내올 수 있다.
Authentication
Authentication는 현재 접근하는 주체의 정보와 권한을 담는 인터페이스이다. Authentication 객체는 Security Context에 저장되며, SecurityContextHolder를 통해 SecurityContext에 접근하고, SecurityContext를 통해 Authentication에 접근할 수 있다.
Principal
유저에 해당하는 정보, 대부분의 경우 Principal로 UserDetails를 반환
GrantAuthority
ROLE_ADMIN, ROLE_USER등 Principal이 가지고 있는 권한을 나타냄
prefix로 'ROLE_"이 붙음, 인증 이후에 인가를 할 때 사용한다.
권한은 여러개 일 수 있기 때문에 Collection<GrantedAuthority> 형태로 제공된다.
<Debug 자주 활용해보자>
SecurityContext를 받아오는 코드를 쳐보고 debuging을 해보면 securityContext가 가지고 있는 정보들을 보여준다.
UsernamePasswordAuthenticationFilter
로그인 인증처리를 담당하고 인증처리에 관련된 요청을 처리하는 필터
좀 더 쉽게
초기 설정
@Configuration
@EnableWebSecurity //웹보안 활성화를위한 annotation
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests() // 요청에 의한 보안검사 시작
.anyRequest().authenticated() //어떤 요청에도 보안검사를 한다.
.and()
.formLogin();//보안 검증은 formLogin방식으로 하겠다.
}
}
자바 10..몇 부터인가 WebSecurityConfigurerAdaptor 못쓰고 SecurityFilterChain 로 바꼈으니 주의!
@EnableWebSecurity 애노테이션을 WebSecurityconfigurerAdapter 를 상속하는 설정 객체에 붙혀주면 SpringSecurityFilterChain에 등록된다.
추가 설정
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()//Form 로그인 인증 기능이 작동함
.loginPage("/login.html")//사용자 정의 로그인 페이지
.defaultSuccessUrl("/home")//로그인 성공 후 이동 페이지
.failureUrl("/login.html?error=true")// 로그인 실패 후 이동 페이지
.usernameParameter("username")//아이디 파라미터명 설정
.passwordParameter("password")//패스워드 파라미터명 설정
.loginProcessingUrl("/login")//로그인 Form Action Url
.successHandler(loginSuccessHandler())//로그인 성공 후 핸들러 (해당 핸들러를 생성하여 핸들링 해준다.)
.failureHandler(loginFailureHandler());//로그인 실패 후 핸들러 (해당 핸들러를 생성하여 핸들링 해준다.)
.permitAll(); //사용자 정의 로그인 페이지 접근 권한 승인
}
}
위와 같은 방식으로 서서히 filte들을 세팅해주면 되는데 정말.. 좋은 블로그를 발견했다
Spring security에 모든게 담겨 있다고해도 과언이 아닌..갓츠비님
<추천 블로그>
https://catsbi.oopy.io/c0a4f395-24b2-44e5-8eeb-275d19e2a536
솔직히 이거 하나보면 흐름이 다 파악된다..
지금 JWT 문제해결하러 가야해서 오늘 블로그는..굉장히 성의없게 여기까지..