[Spring] Spring Security .cors() .and() ISSUE

오두호·2023년 7월 19일

Spring

목록 보기
1/3

프로젝트를 진행하며 SecurityConfig를 작성하던 중이었다.

@Bean
protected SecurityFilterChain configure(HttpSecurity httpSecurity) throws Exception{
		httpSecurity
        .cors().and()
        .csrf().disable()
        .httpBasic.disable()
        .sessionManagement().sessionCreationPolicy(sessionCreationPolicy.STATELESS).and()
        .authorizeRequests().antMatchers("/", "/api/auth/**").permitAll()
        .anyRequest().authenticated();
       

위와 같이 보안 정책을 구성하였는데,
cors().and() IDE가 이런식으로 처리하고, antMatchers 메서드의 경우 컴파일 에러가 발생하였다.

https://docs.spring.io/spring-security/site/docs/current/api/deprecated-list.html
위 문서를 참조해보니, SpringSecurity 7.0에서 제거하기위해 위같은 API는 더이상 지원하지 않는다는 것을 확인할 수 있었다.

정확하지 않지만, 위와 같은 정책을 사용할 때에는 아래와 같이 작성해주니 정상적으로 동작하였다.


    @Bean
    public SecurityFilterChain configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .cors(Customizer.withDefaults())
                .csrf((csrf) -> csrf.disable())
                .httpBasic((httpBasic) -> httpBasic.disable())
                .sessionManagement((sessionManagement)
                        -> sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests((authorizeHttpRequests)
                        -> authorizeHttpRequests.requestMatchers("/", "/api/auth/**").permitAll()
                        .anyRequest().authenticated());

모두 기본값으로 설정하였고, httpbasic, cors정책 등은 각각 프로젝트 내부에서 bearer token, webapp파트에서 적용해주어서 기본값으로 설정한 것이니 참고하길 바란다.

.authorizeRequests().antMatchers("/", "/api/auth/**").permitAll()
        .anyRequest().authenticated();

이 부분을,

    .authorizeHttpRequests((authorizeHttpRequests)
                        -> authorizeHttpRequests.requestMatchers("/", "/api/auth/**").permitAll()
                        .anyRequest().authenticated());

위와 같이 수정해주면 된다. (길어서 따로 뺀 것이고, 위 cors,csrf도 적절히 수정해주어야한다.)

profile
Developer

2개의 댓글

comment-user-thumbnail
2023년 7월 19일

훌륭한 글이네요. 감사합니다.

1개의 답글