implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity'
Spring Security를 사용하기 위해서는 라이브러리를 등록해야 한다.
스프링 시큐리티가 내가 공부하면서 제일 궁금했던 부분이다.
서버의 경우는 어떻게 보안 절차를 해야 하는가?에 대해 나는 제일 궁금했었다.
게임 Bass ( Backend as a Service) 서비스형 백엔드 플랫폼인 Playfab을 사용하면서
보안의 경우는 대부분 function으로 작성했는데 Spring의 경우는 Spring Security를 사용한다.
스프링 시큐리티는 기본적으로 인증되지 않은 사용자는 서비스를 사용할 수 없게끔 막는다.
그렇기 때문에 처음 시큐리티 설정 시 인증을 위한 로그인 화면이 나타나기 마련이다.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests
.requestMatchers(new AntPathRequestMatcher("/**")).permitAll());
return http.build();
}
}
해당 코드는 SecurityConfig 코드로 모든 인증되지 않은 요청을 허락하고 있다.
따라서 로그인하지 않더라도 모든 페이지에 접근할 수 있게 만들었다.
하지만 접속시 403 Forbidden 오류가 발생하는데
이 이유는 스프링 시큐리티를 적용하면 CSRF 기능이 동작하기 때문이다.
스프링 시큐리티 대단하다.. 어떻게 이러한 기능을 ..
참고로 궁금해서 찾아봤는데 CSRF 기능이 없던 시절에는
SameSite 쿠키 속성을 사용하거나 사용자 동의 기반의 방어 Custom 헤더 사용 Referrer 검증 등등
다양한 방법이 사용되었다고 나와있다.
현재도 사용중인 기능도 있겠지만 CSRF 기능이 참 대단하다고 느껴진다.
(... 생략 ...)
@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/**")))
;
return http.build();
}
}
h2 db를 사용하여 테스트를 하고 있기에
다음과 같이 CSRF 처리시 H2 콘솔은 예외로 처리하는 코드를 작성하면 된다.
하지만 위와같은 코드를 작성하면 h2 db가 안들어 가지는데
(... 생략 ...)
@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();
}
}
이렇게 X-Frame_options 헤더값을 sameorigin으로 설정하여 오류가 발생하지 않도록 하면 된다.
'BackEnd > Spring' 카테고리의 다른 글
Spring Boot 게시판 만들기 연습.. (0) | 2023.12.12 |
---|---|
Repository (0) | 2023.11.22 |
Entity (0) | 2023.11.22 |
스프링 부트 Validation (0) | 2023.11.17 |
스프링 부트 Controller (1) (1) | 2023.11.14 |
Comment