[Spring boot] Spring Security CSRF 오류 해결 및 Spring 6.0 이후 Config 설정 법

90000e·2023년 9월 13일
9

[Spring]

목록 보기
1/8

프로젝트에서 spring security를 사용하는 중인데, spring 6.0 이후부턴 Adapter을 상속받아오지 못하고, Bean으로 등록해야 한다고 한다.

이렇게 바뀌면서 좀 많은 부분이 바뀐거같아 바뀐부분과 CSRF오류에대해 작성해보도록 하겠다.

👍변경 전

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserService userService;

    @Value("${jwt.secret}")
    private String secretKey;

    //https://www.youtube.com/watch?v=YEB0Ln6Lcyk&ab_channel=KyeongrokKim 8:51
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf().disable()
                .authorizeRequests()
                // 특정 API에 대해 모든 사용자에게 접근 허용
                .antMatchers("/user/register").permitAll()
                .antMatchers("/board/return").permitAll()
                .antMatchers("/user/login").permitAll()
                .antMatchers("/search/recommand").permitAll()
                .antMatchers("/search/updateData").permitAll()
                // --------------------------------------------
                .anyRequest().authenticated() // 나머지 API에 대해서는 인증을 요구
                .and()
                .addFilterBefore(new JwtFilter(userService, secretKey), UsernamePasswordAuthenticationFilter.class);
    }
}

이렇게 WebSecurityConfigurerAdapter를 상속받아 configure 메서드를 Override해서 사용했었다. 내가 알고있는 바뀐부분에대해 정리해보겠다.

  1. Override -> Bean등록으로 변경
  2. authorizeRequests() -> authorizeHttpRequests()
  3. antMatchers() -> requestMatchers()
  4. access() -> hasAnyRole()
  5. http.build()를 꼭 반환해 줘야함

이렇게 5가지 정도 바뀐것같다. 아직 바뀐지 얼마 되지않아 이런 글이 많이 없는것같아 정리한다.

👍변경 후

public class WebSecurityConfig {

    private final UserService userService;

    @Value("${jwt.secret}")
    private String secretKey;

    @Bean
    protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                // 특정 API에 대해 모든 사용자에게 접근 허용
                .requestMatchers("/user/register").permitAll()
                .requestMatchers("/board/return").permitAll()
                .requestMatchers("/user/login").permitAll()
                .requestMatchers("/search/recommand").permitAll()
                .requestMatchers("/search/updateData").permitAll()
                .requestMatchers("/chat/room").permitAll()
                // --------------------------------------------
                .anyRequest().authenticated() // 나머지 API에 대해서는 인증을 요구
                .and()
                .addFilterBefore(new JwtFilter(userService, secretKey), UsernamePasswordAuthenticationFilter.class);
        http
                .cors(cors -> cors.disable())
                .csrf(csrf -> csrf.disable());
        return http.build();
    }
}

이렇게 변경이 됐는데 내가 명시한 부분외에도 바뀐부분이 존재한다. 그 부분은 바로 cors csrf부분이다. 이건 spring 6.0 이후에 바뀐건지는 잘 모르겠지만 내 데스크탑과 노트북에선 빌드는 되지만 빨간줄이 그어져 설정 적용이 되지않았다...

spring security 본문을 찾아보니

http
	.cors()
	.and()
	.csrf().disable(); //변경 전
http
	.cors(cors -> cors.disable())
	.csrf(csrf -> csrf.disable()); //변경 후

로 사용하면 된다고 한다!
이렇게 오류를 바로 잡을 수 있었다!

profile
내가 복습하려고 쓰는 블로그

6개의 댓글

comment-user-thumbnail
2023년 9월 13일

오~

1개의 답글
comment-user-thumbnail
2023년 9월 14일

유익한 글이네요~

1개의 답글
comment-user-thumbnail
2023년 11월 28일

도움이 많이 되었습니다~

1개의 답글