[Springboot] 스프링부트 3.x(3.0)이상 버전 SecurityFilterChain 설정

푸른별·2023년 8월 18일
0

Web

목록 보기
12/16
post-thumbnail

글을 쓰게 된 이유

스프링부트 3.x버전과 자바 17을 사용하여 스프링부트 시큐리티 관련 코드를 작성 중이었습니다.
그런데 평소처럼 코드를 사용하던 차에 이런 오류가 발생했습니다.

(??? 대체 내가 뭘 잘못했다고..)

기존에는 이렇게 써도 문제가 없었고, http.csrf().disable()로 csrf를 비활성화하는 방식이었는데, 스프링부트 2.x버전이 문제라고 생각해서 직접 알아봤습니다.

공식 문서 및 깃허브에 접근해서 확인해본 결과, 버전업이 되며 코드 스타일이 달라진 것이 확연하게 보였습니다.

따라서 저 또한 다음과 같이 코드를 변경해주었습니다.

수정된 코드

스프링부트 2.x

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.csrf().disable();
	http.authorizeRequests()
			.antMatchers("/user/****").authenticated()
			.antMatchers("/admin/****").access("hasRole('ROLE_ADMIN')")
			.anyRequest().permitAll()
			.and()
			.formLogin()
			.loginPage("/login")
			.loginProcessingUrl("/loginProc")
			.defaultSuccessUrl("/")
			.and()
			.oauth2Login()
			.loginPage("/login")
			.userInfoEndpoint()
			.userService(principalOauth2UserService);
	return http.build();
    }

스프링부트 3.x

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    	return http.
            csrf(AbstractHttpConfigurer::disable)                
            .authorizeHttpRequests((authorizeRequests) ->
                    authorizeRequests
                            .requestMatchers("/user/****").authenticated()
                            .requestMatchers("/admin/****").hasRole("ROLE_ADMIN")
                            .anyRequest().permitAll()
            )
            .formLogin(login -> login
                    .loginPage("/login")
                    .loginProcessingUrl("/loginProc")
                    .defaultSuccessUrl("/")
            )
            .oauth2Login(oauth2Configurer -> oauth2Configurer
                    .loginPage("/login")
                    .userInfoEndpoint(userInfo ->
                            userInfo.userService(principalOauth2UserService))
            )
            .getOrBuild();
}
  • 이전처럼 and()로 chaining이 되지 않아 코드가 기능별로 분류가 잘 된 것이 눈에 확연이 띄는 것이 장점이라고 생각합니다.

  • 몇 가지 명칭이 변경된 점이 있습니다.
    authorizeRequests -> authorizeHttpRequests
    antMatchers -> requestMatchers
    build -> getOrBuild

Reference

  1. https://spring.io/projects/spring-security#samples
  2. https://github.com/spring-projects/spring-security-samples/blob/main/servlet/spring-boot/java/hello-security-explicit/src/main/java/example/SecurityConfiguration.java
profile
묵묵히 꾸준하게

0개의 댓글