Spring 기반 App 의 인증과 권한을 담당하는 Spring 의 하위 framework 이다.

  • 인증 (Authenticate) - 로그인
  • 권한 (Authorize) - 인증된 사용자가 어떤 것을 할 수 있는지

✏️ Spring Security 시작하기

📍 Dependencies

  • hymeleaf-extras-springsecurity6 는 Spring boot 가 관리하는 패키지가 아니기 때문에 별도의 버전정보를 적어주어야 한다.
    • 미래에는 버전 정보 없이 사용될 수도 있다.
    • 버전정보 없이 쓸 수 있으면 그게 더 좋은거니까 없이 쓰면 된다.
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6:3.1.1.RELEASE'

📍 서버 실행

  • 디펜던시를 설치하고 서버를 재시작하면 Spring Security 가 자동으로 로그인 화면을 띄워준다.
    • 기본적으로 인증되지 않은 사용자는 서비스를 이용할 수 없게 되어있다.

  • 기본적인 조회기능은 인증없이도 사용할 수 있게 만드는 기능이 필요하다.

📍 Configuration 계층

  • @EnableWebSecurity
    • 모든 요청 URL 이 Spring Security 의 제어를 받도록 한다.
    • 내부적으로 SpringSecurityFilterChain이 동작하여 URL 필터가 적용된다.
  • SecurityFilterChain
    • Spring Security 의 세부 설정을 할 수 있다.
    • 아래의 코드에서 해준 설정은 인증되지 않은 모든 요청을 허락한다는 의미이다.
      • 로그인을 하지 않아도 모든 페이지에 접근할 수 있음
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().requestMatchers(
                new AntPathRequestMatcher("/**")
        ).permitAll();
        return http.build();
    }
}

✏️ H2 오류 해결

📍 H2 403 Forbidden

위의 방법으로 보안설정을 하면 H2 에서 403 오류가 발생한다.

  • CSRF 기능이 동작하기 때문
  • H2 콘솔은 CSRF 토큰 발행기능이 없어 발생하는 오류이다.

⚠️ CSRF - Cross Site Request Forgery

  • 웹사이트의 취약점 공격을 방지하기 위한 기술
  • Spring Security 가 세션을 통해 CSRF 토큰값을 발행하고,
    웹 페이지는 요청시 토큰을 함께 전송해 실제 웹 페이지에서 작성된 Data 가 전달되는지 검증하는 기술이다.
  • Security 옵션 설정으로 문제를 해결할 수 있다.
    • H2 콘솔만 CSRF 기능을 예외로 설정해야 한다.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests().requestMatchers(
                new AntPathRequestMatcher("/**")).permitAll()
            // h2 에서 CSRF 기능을 예외로 처리하는 로직
            .and()
                .csrf().ignoringRequestMatchers(
                        new AntPathRequestMatcher("/h2-console/**"))
            ;
        return http.build();
    }
}

📍 H2 화면 깨짐 현상

H2 의 콘솔 화면은 Frame 구조로 되어있고,

Spring Security 는 사이트의 콘텐츠가 다른 사이트에 포함되지 않도록 하기 위해 X-Frame-Options 해더값을 사용해 이를 방지하기 때문에 화면이 깨지게 된다.

  • Security 를 설정해 문제를 해결할 수 있다.
    • XFrameOptionsheart 값을 sameorigin 로 설정해 주면 된다.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests().requestMatchers(
                new AntPathRequestMatcher("/**")).permitAll()
            .and()
                .csrf().ignoringRequestMatchers(
                        new AntPathRequestMatcher("/h2-console/**"))
            // 화면 깨짐 문제 해결 로직
            .and()
                .headers()
                .addHeaderWriter(new XFrameOptionsHeaderWriter(
                        // 헤더값 변경
                        XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))
            ;
        return http.build();      
    }
}
profile
잘못된 내용 PR 환영

0개의 댓글