스프링 시큐리티는 스프링 기반 웹 어플리케이션의 인증과 권한을 담당하는 하위 프레임워크다.
인증 및 인가
인증은 로그인한 ID가 진짜 권한이 있는 사용자인가 체크 하는것이고 인가는 로그인 하는 사용자가 어떤 권한을 가지고 무엇을 할 수 있는가 하는 보안의 핵심이다.
SecurityFilterChain
Spring Security는 표준 서블릿 필터를 기반으로 동작하는데요. SpringBoot의 기본 설정을 사용하는 경우, 인증에 사용되는 Filter들이 모여있는 SecurityFilterChain을 자동으로 등록해주는데, 이 SecurityFilterChain을 통해 스프링 시큐리티의 인증 과정이 동작하게 됩니다.
FormLogin 인증
웹페이지에서 사용자ID와 비밀번호을 입력하여 POST방식으로 서버에 전송하여 인증하는 방식입니다.
인증없이 페이지 접근시 로그인 페이지로 이동 시킵니다.
@Configuration
@EnableWebSecurity
public class SecurityConfig{
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
http.
authorizeHttpRequests((auth) -> auth
.requestMatchers("/","/login", "/loginProcess").permitAll()
.requestMatchers("/admin").hasRole("ADMIN")
.requestMatchers("/home/**").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated()
);
http.
formLogin()
.loginPage("/login")
.defaultSuccessUrl("/main")
.loginProcessUrl("/login/process"); //formLogin방식으로 로그인 하기위한 설정
return http.build();
}
}
HttpBasic 인증
id와 비밀번호를 base64방식으로 인코딩 한 뒤 HTTP 인증 헤더에 부착하여 서버측으로 요청을 보내는 방식
스프링시큐리티를 적용하기 위한 아래 설정을 합니다.
@Configuration
@EnableWebSecurity
public class SecurityConfig{
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
http.
authorizeHttpRequests((auth) -> auth
.requestMatchers("/","/login", "/loginProcess").permitAll()
.requestMatchers("/admin").hasRole("ADMIN")
.requestMatchers("/home/**").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated()
);
http.
httpBasic(Customizer.withDefaults()); //httpbasic방식으로 로그인 하기위한 설정
http.
csrf((auth) -> auth.disable());
return http.build();
}
}
인증 된 정보 얻기
SecurityContext : Authentication객체가 보관되는 저장소 역할
SecurityContextHolder : SecurityContext객체를 보관하고 있는 wrapper 클래스
Authentication : 접근 주체의 인증 정보와 권한을 담는 인터페이스
principal : 접근 주체의 아이디 혹은 User객체를 저장합니다.
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
UserDTO userInfo = (UserDTO)principal;
'웹개발 > spring && springboot' 카테고리의 다른 글
스프링 AOP의 정의 (0) | 2024.02.23 |
---|---|
[springboot]thymleaf(타임리프) (0) | 2024.02.23 |
스프링 컨트롤러 url매핑 정의 (0) | 2024.01.29 |
Controller와 RestController 차이 (2) | 2024.01.29 |
Spring과 Springboot의 차이 (0) | 2024.01.29 |