Spring/Spring boot
Spring Security H2 데이터 베이스 사용시 프레임 오류
java나유
2022. 10. 27. 15:14
스프링 시큐리티를 사용하면 자동으로 CSRF 토큰이 생성된다.
측정 페이지 url은 스프링 시큐리티를 해제할 수 있지만, 그 상태로 H2에 접속이 불가하다.
H2 콘솔은 스프링과 상관없는 일반 애플리케이션이기 때문에 예외처리를 해주어야한다.
문제화면:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll()
.and()
.csrf().ignoringAntMatchers("/h2-console/**")
;
return http.build();
}
}
- and() - http 객체의 설정을 이어서 할 수 있게 하는 메서드이다.
- http.csrf().ignoringAntMatchers("/h2-console/**") - /h2-console/로 시작하는 URL은 CSRF 검증을 하지 않는다는 설정이다.
이렇게 수정하면
프레임이 깨져서 보이게된다. 원인은 H2 콘솔 화면이 frame구조인데, X-Frame-Options 헤더값을 사용해서 이를 방지 할 수 있다.
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll()
.and()
.csrf().ignoringAntMatchers("/h2-console/**")
.and()
.headers()
.addHeaderWriter(new XFrameOptionsHeaderWriter(
XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))
;
return http.build();
}
}
이제 다시 H2 콘솔로 로그인하면 정상 동작하는 것을 확인할 수 있다.
728x90