스프링 시큐리티

suhan cho·2022년 7월 29일
0

스프링 시큐리티

스프링 기반 애플리케이션의 인증과 권한을 담당하는 스프링 하위 프레임워크

  • 인증은 로그인을 의미
  • 권한은 인증된 사용자가 어떤 것을 할 수 있는지 의미

설치

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

  • 이런식으로 접속하면 바로 로그인 화면이 나온다.
  • 로그인 없이도 게시물을 조회가능 하도록 수정한다

로그인 없이 조회가능 하도록

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        http.authorizeRequests().antMatchers("/**").permitAll();
        return http.build();
    }
}
  • @Configuration 스프링의 환경설정 파일임을 의미
    여기서는 스프링 시큐리티의 설정을 위해 사용
  • @EnableWebSecurity 모든 요청 URL이 스프링 시큐리티의 제어를 받도록
  • SecurityFilterChain 빈을 통해 생성
  • http.authorizeRequests().antMatchers("/**").permitAll()
    인증되지 않은 요청을 허락한다는 의미

CSRF

위와 같은 과정을 하여도 403오류가 발생한다
그 이유는 스프링 시큐리티의 CSRF기능 때문이다

CSRF란

  • 웹 사이트 취약점 공격을 방지 위해 사용하는 기술
  • CSRF토큰 값을 세션을 통해 발행하고 웹 페이지에서는 폼 전송시에 해당 토큰을 함께 전송하여 실제 웹 페이지에서 작성된 데이터가 전달되는지 검증하는 기술

<input type="hidden" name="_csrf" value="0d609 ~~~~"/>
  • form태그에 csrf토큰이 자동으로 생성된다.
  • 스프링 시큐리티에 의해 csrf토큰의 값이 정확한지 검증 과정 거침
  • csrf값이 없거나 임의의 csrf값을 강제로 만들어 전송하는 악의적인 URL요청은 스프링 시큐리티에 의해 블록킹 된다(H2는 csrf토큰 발행 기능 없음)
@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검증 받지 않는다.

출처: https://wikidocs.net/162150

profile
안녕하세요

0개의 댓글