
2년 전 만들어놓은 프로젝트를 다시 찾아보면서 여러 문제를 맞이하고 있습니다.
제 생각에는 AWS, Docker로 서버 세팅까지 해놨으니 다시 올리면 그대로 성공할 줄 알았는데요.
급하게 만드느라고 고려하지 않은 것들이 문제로 드러났습니다. 이 문제도 동일합니다.
- 프로젝트는 React, Spring boot로 프론트와 백엔드를 구분해서 만들었습니다.
- AWS 프리티어를 모두 사용해서, Cloudtype을 사용했습니다.
- Spring Security 의존성은 비밀번호 암호화를 위해 사용하고 있었습니다.
문제: CORS 오류
로컬에서 프론트엔드 서버와 백엔드 서버끼리 소통할 때는 문제가 없었는데, 서버에 올라가고 나서 CORS 정책으로 인해 요청이 차단되는 문제가 발생했습니다.
이 문제는 이전에 해결한 뒤 Front - Back 서버를 분리하면서 만난 CORS 정책라는 제목으로 이 블로그에 정리해뒀습니다.
@EnableJpaAuditing
@SpringBootApplication
public class ServerBackendApplication implements WebMvcConfigurer {
publicstaticvoidmain(String[] args) {
SpringApplication.run(ServerBackendApplication.class, args);
}
@OverridepublicvoidaddCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins(
"http://localhost:3000",
"https://web-advise-clothes-front-am952nlt1gbj1t.sel5.cloudtype.app"
)
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
}
이미 해결된 코드인데 왜 다시 똑같이 발생하는 걸까? 고민하며 찾아보니 Spring MVC과 Spring Security에서 CORS 설정이 따로 있는 것을 알게 되었습니다. 제 코드는 Spring MVC에서 Origin을 등록하는 정책이었습니다.
시도1: Spring Security에서 CORS 정책 비활성화
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().disable() // CORS 비활성화 시도
.httpBasic().disable()
.csrf().disable();
}
}
httpBasic().disable()
, csrf().disable()
은 이전에 해놓은 설정이기 때문에, 위에 .cors().disable()
코드를 추가했습니다. 하지만 작동하지 않았습니다.시도2: 변경된 Spring Security 정책에 따른 해결
이번엔 왜 disable이 되지 않는지 찾아본 결과, Spring 블로그에서 찾아볼 수 있었습니다. 아래 권장사항대로 Spring Security의 CORS를 비활성화 했습니다.
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors(AbstractHttpConfigurer::disable)
.httpBasic().disable()
.csrf().disable();
}
이후 배포하니 프론트 서버에서 CORS 정책으로 막히지 않게 되었습니다.
심화: SecurityFilterChain 사용
문제의 원인을 찾던 중
WebSecurityConfigurerAdapter
를 설계에 결함이 있어 사용하지 않는다고 합니다. 이유는 아래와 같습니다.- 설정을 조용히 처리함
- 보안 구성이 메서드 인수로 Bean을 전달하는 모범 사례를 따르지 않는다는 것. (종속성을 파악하기 어려움 등.)
권장 사항에 따라 SecurityFilterChain 빈을 등록해서 Spring Security 설정을 했습니다.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.cors(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable);
returnhttp.build();
}
}
참고 링크
- 시도
- 심화
Share article