티스토리 뷰

에러 메세지

Cannot resolve method 'and' in 'HttpSecurity'
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .cors().configurationSource(corsConfigurationSource()).and()
            .authorizeRequests()
            .antMatchers("/api/v1/users/*").permitAll()
            .antMatchers("/api/v1/login").permitAll()
            .antMatchers("/api/v1/profile").permitAll()
            .anyRequest().authenticated()
            .and()
            .httpBasic().disable()
            .formLogin().disable()
            .and()  // 여기서 에러 발생
            .apply(new JwtConfigurer(jwtTokenProvider))
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
            .accessDeniedHandler(new CustomAccessDeniedHandler());

    return http.build();
}

 

원인

HttpSecurity 객체에서 and() 메서드를 찾을 수 없을 때 발생한다.

빌더 패턴을 사용할 때 메서드 호출 순서에 문제가 있을 때 발생하는 에러 !!

 

HttpSecurity 객체의 모든 구성이 단일 체인으로 되어있는 상태에서 exceptionHandling() 메서드 다음에 and()를 호출하려고 하면 에러가 발생한다.

exceptionHandling() 메서드는 ExceptionHandlingConfigurer 타입의 객체를 반환하는데 세개의 특정 메서드만 사용할 수 있다.

  • accessDeniedHandler(AccessDeniedHandler accessDeniedHandler): 액세스 거부 처리
  • accessDeniedPage(String accessDeniedPage): 액세스 거부 시 사용자를 리다이렉트할 페이지의 URL을 설정
  • authenticationEntryPoint(AuthenticationEntryPoint authenticationEntryPoint): 인증되지 않은 사용자의 요청을 처리

하지만 and 메서드는 ExceptionHandlingConfigurer 클래스에 없고 HttpSecurity 클래스에 있어서

exceptionHandling() 후에 and() 메서드를 호출하려면 구성 체인을 나누어서 처리해야 한다.

 

 

해결방법

두 개의 별도의 구성 체인으로 나누어서 만든다.

 

apply() 메서드 이전에 호출하던 and() 메서드를 삭제하고, exceptionHandling() 메서드를 다른 체인으로 분리해서 호출하는 걸로 바꿨다.

  • 첫 번째 체인 : http 객체를 구성하고, JwtConfigurer를 적용
  • 두 번째 체인 : exceptionHandling() 구성
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .cors().configurationSource(corsConfigurationSource()).and()
            .authorizeRequests()
            .antMatchers("/api/v1/users/*").permitAll()
            .antMatchers("/api/v1/login").permitAll()
            .antMatchers("/api/v1/profile").permitAll()
            .anyRequest().authenticated()
            .and()
            .httpBasic().disable()
            .formLogin().disable()
            .apply(new JwtConfigurer(jwtTokenProvider));

    http.exceptionHandling()
            .authenticationEntryPoint(new CustomAuthenticationEntryPoint())
            .accessDeniedHandler(new CustomAccessDeniedHandler());

    return http.build();
}

 

 

 

빌드 패턴.. 디자인 패턴에 대해서 공부를 해야겠다 어서 😓

반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함