스프링 시큐리티를 사용하면 자동으로 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
'Spring > Spring boot' 카테고리의 다른 글
BindingResult 와 rejectValue 스프링 회원가입 유효성 검사 (0) | 2022.11.03 |
---|---|
java: constructor () is already defined in class lombok 오류 해결 (0) | 2022.11.02 |
페이징 구현하기 (0) | 2022.10.27 |
Spring Boot Validation // null로 등록 불가능하게 하는 방법 (0) | 2022.10.27 |
MAC m1 H2 Databases 설치 방법 (0) | 2022.10.26 |
댓글