Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

hy6

3-05 스프링 시큐리티 (실습 기록) 본문

점프 투 스프링 부트

3-05 스프링 시큐리티 (실습 기록)

rantinum 2023. 10. 31. 12:51

스프링 시큐리티

  • 스프링 시큐리티 : 스프링 기반 애플리케이션의 인증과 권한을 담당하는 스프링의 하위 프레임워크
  • 인증(Authenticate) : 로그인을 의미
  • 권한(Authorize) : 인증된 사용자가 어떤 것을 할 수 있는지를 의미

스프링 시큐리티 설치

  • build.gradle에 설치를 해보자
  • build.gradle
(... 생략 ...)
dependencies {
    (... 생략 ...)
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6:3.1.1.RELEASE'
}
(... 생략 ...)

  • 그러면 이런 화면이 나올것이다. 스프링 시큐리티는 기본적으로 인증되지 않은 사용자는 서비스를 사용할 수 없게끔 되어 있다. 그런 이유로 해당 화면이 나오는데, sbb의 열람은 모두가 가능해야 하므로 이를 시큐리티 설정을 통해 바로잡아야 한다.

  • SecurityConfig.java 파일을 작성하자.

  • SecurityConfig.java

    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()) ; return http.build(); 
    }
    }
  • @Configuration : 스프링의 환경설정 파일임을 의미하는 애너테이션

  • @EnableWebSecurity : 모든 요청 URL이 스프링 시큐리티의 제어를 받도록 만드는 애너테이션

  • @EnableWebSecurity 애너테이션을 사용하면 내부적으로 SpringSecurityFilterChain이 동작하여 URL 필터가 적용된다.

  • 하지만 실행하면 이런 403 에러코드가 뜬다. 이유는 스프링 시큐리티를 적용하면 CSRF 기능이 동작하기 때문이다.
  • CSRF : 웹 사이트 취약점 공격을 방지를 위해 사용하는 기술. 클라이언트는 서버의 통신에 올바른 CSRF 토큰을 포함해야 한다. 그렇지 않으면 서버는 요청된 작업 수행을 거부한다.
  • 다음과 같이 설정 파일을 수정하자.
  • SecurityConfig.java
(... 생략 ...)
@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콘솔의 화면은 frame으로 작성되어 있다. 스프링 시큐리티는 사이트의 콘텐츠가 다른 사이트에 포함되지 않도록 하기 위해 X-Frame-Options 헤더값을 사용하여 이를 방지한다. (clickjacking 공격을 막기위해 사용함)

  • 다음과 같이 수정하자.

  • SecurityConfig.java

package com.mysite.sbb;
(... 생략 ...)
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;
(... 생략 ...)
@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();
    }
}
  • 위 처럼 URL 요청시 X-Frame-Options 헤더값을 sameorigin으로 설정하여 오류가 발생하지 않도록 했다.

  • 이제 적용하고 다시 로컬서버에서 H2콘솔창을 진입하면 잘 작동 될 것 이다.