SpringBoot/개인프로젝트

Ajax가 작동이 되지 않는 문제

ewok 2023. 5. 1. 13:00

Ajax를 통해 서버로 통신을 시도해도 계속 403에러가 발생하였다. 이 경우 Spring Security를 사용한다면 csfr 보호 기능이 활성화 되어있는지 확인해보자

 

Spring Security를 사용한다면 보통 csrf 보호기능이 활성화 되어 있는데, 이러면 Ajax로 통신을 할 수가 없었다.

CSFR(Cross-Site Request Forgery) - 사이트 간 요청 위조
사용자가 자신의 의지와는 무관하게 공격자가 의도한 행위를 특정 웹사이트에 요청하게 하는 공격

 

일단은 SecurityConfig에서 

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.headers().frameOptions().disable();
    http.authorizeRequests()
            .antMatchers("/h2-console/**").permitAll()
            .anyRequest()
            .permitAll()
            .and()
            .csrf().ignoringAntMatchers("/h2-console/**", "/api/**")
            .and()
            .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET")).clearAuthentication(true)
            .logoutSuccessUrl("/")
            .and()
            .oauth2Login()
            .defaultSuccessUrl("/")
            .userInfoEndpoint().userService(customOAuth2UserService);
    return http.build();
}

ajax를 사용하는 /api/** 부분을 csfr().ignoringAntMatchers()에 넣어 해결하였다.