SpringSecurity란?
스프링시큐리티는 스프링 기반 애플리케이션의 인증과 권한을 담당하는 스프링의 하위 프레임워크이다.
- 인증(Authenticate)는 로그인을 의미
- 권한(Authorize)는 인증된 사용자가 어떤 것을 할 수 있는지를 의미한다.
package com.mysite.sbb;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests
.requestMatchers(new AntPathRequestMatcher("/**")).permitAll())
.csrf((csrf) -> csrf
.ignoringRequestMatchers(new AntPathRequestMatcher("/h2-console/**")))
.headers((headers) -> headers
.addHeaderWriter(new XFrameOptionsHeaderWriter(
XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN)))
;
return http.build();
}
}
@EnableWebSecurity는 Spring security의 기본 설정을 활성화하고, 'WebSecurityConfigurerAdapter' 클래스를 상속한 설정 클래스를 만들어서 필요한 보안 설정을 추가할 수 있도록 한다.
SecurityFilterChain은 Spring Security의 필터 체인을 정의하는 역할을 한다. filterChain 메서드는 HttpSecurity를 매개변수로 받아서 보안 구성을 설정하고 필터 체인을 반환한다.
http.authorizeHttpRequests(...)는 요청에 대한 인가 규칙을 정의한다. authorizeHttpRequests 메서드 내에서는 AntPathRequestMatcher를 사용하여 특정 패턴의 요청에 대한 권한 설정을 지정한다. 여기서는 모든 경로("/**")에 대해 권한을 부여하도록 설정되어 있다.
CSRF(cross site request forgery)는 웹 사이트 취약점 공격을 방지를 위해 사용하는 기술. 스프링 시큐리티가 CSRF 토큰 값을 세션을 통해 발행하고 웹 페이지에서는 폼 전송시에 해당 토큰을 함께 전송하여 실제 웹 페이지에서 작성된 데이터가 전달되는지를 검증하는 기술이다.
.csrf((csrf) -> csrf
.ignoringRequestMatchers(new AntPathRequestMatcher("/h2-console/**")))
h2에는 csrf토큰을 발행해주는 기능이 없어 오류가 발생하기에 h2콘솔에 대한 csrf기능의 예외처리코드
.headers((headers) -> headers
.addHeaderWriter(new XFrameOptionsHeaderWriter(
XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN)))
스프링 시큐리티는 사이트의 콘텐츠가 다른 사이트에 포함되지 않도록 하기 위해 X-Frame-Options 헤더값을 사용하여 이를 방지한다. (clickjacking 공격을 막기위해 사용함)
위 처럼 URL 요청시 X-Frame-Options 헤더값을 sameorigin으로 설정하여 오류가 발생하지 않도록 했다. X-Frame-Options 헤더의 값으로 sameorigin을 설정하면 frame에 포함된 페이지가 페이지를 제공하는 사이트와 동일한 경우에는 계속 사용할 수 있다.