[점프 투 스프링] Spring Security 설정하기

Honam Kim·2024년 12월 11일
post-thumbnail

깃허브 링크 : https://github.com/tigerpoint123/jsb-20241210

Spring Security ?

스프링 기반 웹 애플리케이션의 인증과 권한을 담당하는 스프링의 하위 프레임워크
이때, 인증(authenticate)은 사용자의 신원 확인 등, 권한(authrize)은 인증된 사용자가 어떤 일을 할 수 있는지 관리하는 것이다.

설치하기

먼저 build.gradle에 코드를 추가합니다.

    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'

그리고 바로 서버를 키면 다음과 같은 화면이 맞이해요.

이유는 간단합니다. 인증되지 않은 사용자가 서비스를 이용하지 못하게 막고 있어요 지금.

그래서 스프링 시큐리티의 설정을 담당할 SecurityConfig 클래스를 만들어줍니다.

@Configuration // == 스프링의 환경 설정 파일임을 명시함.
@EnableWebSecurity // 모든 요청 URL이 스프링 시큐리티의 제어를 받도록 만듦.
public class SecurityConfig {
    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    // 로그인하지 않아도 모든 페이지에 접근할 수 있도록 설정.
        http
            .authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests
                .requestMatchers(new AntPathRequestMatcher("/**")).permitAll())
        ;
        return http.build();
    }
}

Bean 어노테이션

@Bean : 스프링에 의해 생성/관리되는 객체를 의미. 컨트롤러, 서비스, 리포지터리가 이에 해당

그리고 이 시큐리티는 h2 데이터베이스 접근도 막기 때문에, 따로 허용을 해줘야 한다. 이때 csrf 토큰이 등장함.

CSRF

csrf는 웹 보안 공격 중 하나로, 조작된 정보로 웹사이트가 실행되도록 속이는 공격기술임.

스프링 시큐리티는 이것을 방지하기 위해 csrf 토큰을 세션에 발행하고, 웹 페이지에서는 폼 전송 시

해당 토큰을 전송하여 실제 웹 페이지에서 작성한 데이터가 전달되는지를 검증한다.

위에서 만든 SecurityConfig 클래스를 수정해줘요

@Configuration // == 스프링의 환경 설정 파일임을 명시함.
@EnableWebSecurity // 모든 요청 URL이 스프링 시큐리티의 제어를 받도록 만듦.
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 연결을 하면

이런 화면이 다시 뜹니다.

스프링 시큐리티는 웹사이트의 콘텐츠가 다른 사이트에 포함되지 않도록 하기 위해 X-Frame-Options 헤더의 기본값을 DENY로 하는데, 이럴경우 오류가 발생함.

스프링부트에서 X-Frame-Options 헤더는 클릭재킹(사용자의 의도와 다른 작업이 수행되도록 속이는 보안기술)을 막기 위해 사용.

따라서 아래처럼 코드를 수정해줌.

@Configuration // == 스프링의 환경 설정 파일임을 명시함.
@EnableWebSecurity // 모든 요청 URL이 스프링 시큐리티의 제어를 받도록 만듦.
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();
    }
} 

설정 끝 ~

profile
자유로운영혼

0개의 댓글