• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

커스텀 필터 적용 안됨

23.09.09 13:39 작성 조회수 620

0

강의를 다 수강하고 깃허브 코드 참조하여 작성했습니다.

현재 SecurityConfig 코드는 다음과 같습니다.

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig{
    private final UserRepository userRepository;
    private final CorsConfig corsConfig;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement((sessionManagement) ->
                        sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                .formLogin(withDefaults())
                .httpBasic(withDefaults())
                .apply(new MyCustomDsl())
                .and()
                .authorizeRequests(requests -> requests
                        .requestMatchers("/user/**").authenticated()
                        .requestMatchers("/admin/**").access("hasAuthority('ADMIN')")
                        .anyRequest().permitAll()
                )
        .build();
    }

    public class MyCustomDsl extends AbstractHttpConfigurer<MyCustomDsl, HttpSecurity> {
        @Override
        public void configure(HttpSecurity http) throws Exception {
            AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
            http
                    .addFilter(corsConfig.corsFilter())
                    .addFilter(new JwtAuthenticationFilter(authenticationManager))
                    .addFilter(new JwtAuthorizationFilter(authenticationManager, userRepository));
        }
    }
}

filterchain에서 and()에 오류가 발생합니다.

'and()' is deprecated and marked for removal

로 나오는데 and가 deprecated된 거 같지는 않고 커스텀 필터를 적용하는 것에서 뭔가 문제가 있지 않을까 싶습니다만 이틀째 해결을 못하고 있어 문의남깁니다ㅠㅠ

 

답변 1

답변을 작성해보세요.

0

유은혜님의 프로필

유은혜

질문자

2023.09.09

@Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);
        return http
                .csrf(AbstractHttpConfigurer::disable)
                .sessionManagement((sessionManagement) ->
                        sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                .formLogin(withDefaults())
                .httpBasic(withDefaults())
                .addFilter(corsConfig.corsFilter())
                .addFilter(new JwtAuthenticationFilter(authenticationManager))
                .addFilter(new JwtAuthorizationFilter(authenticationManager, userRepository))
                .authorizeRequests(requests -> requests
                        .requestMatchers("/user/**").authenticated()
                        .requestMatchers("/admin/**").access("hasAuthority('ADMIN')")
                        .anyRequest().permitAll()
                )
        .build();
}

커스텀 필터를 적용 안하고 커스텀 필터에 코드를 filterchain에 작성하면 어떨까 싶어

위와 같이 작성해보았었으나, 빨간 줄은 안 뜨지만 디버깅해보니 authenticationManager가 null이라고 나왔었습니다..

https://github.com/codingspecialist/Springboot-Security-JWT-Easy/blob/version3/src/main/java/com/cos/jwtex01/config/SecurityConfig.java

 

제 깃헙에 브랜치가 총 3개 있어요!! 여기서 소스코드 보고 작성하시면 되요

msun0215님의 프로필

msun0215

2023.11.17

늦었지만 제 해결 사례를 알려드리자면,,

http 객체에 쭉 이어서 붙이지 마시고 and() 부분에서 한번 끊고 다시 연결시니까 해결이 되었습니다

 

        http.csrf(cs-> cs.disable())
                .sessionManagement(s->s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                        .formLogin(f->f.disable())
                                .httpBasic(h->h.disable())
                                        .apply(new MyCustomDs1());   // custom Filter
                //.addFilter(new JWTAuthenticationFilter(authenticationManager))
                //.addFilter(new JWTAuthorizationFilter(authenticationManager, userRepository))
        http.authorizeHttpRequests(authorize-> {     // 권한 부여
                    // authorizeRequests가 deprecated됨에 따라 authorizeHttpRequests 사용 권장
                    authorize
                            .requestMatchers("/user/**").hasAnyRole("hasRole('ROLE_USER') or hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')")
                            .requestMatchers("/manager/**").hasAnyRole("hasRole('ROLE_MANAGER') or hasRole('ROLE_ADMIN')")
                            .requestMatchers(("/admin/**")).hasAnyRole("hasRole('ROLE_ADMIN')")

//                            .requestMatchers("/user/**").hasAnyAuthority("USER","MANAGER","ADMIN")
//                            .requestMatchers("/user/**").authenticated()
//                            .requestMatchers("/manager/**").hasAnyAuthority("MANAGER", "ADMIN")
//                            .requestMatchers("/manager/**").access("hasAuthority('ROLE_ADMIN')")
//                            .requestMatchers(("/admin/**")).hasAuthority("ADMIN")
                        .anyRequest().permitAll();  // 이외의 요청은 모두 허용함
                });

        /* Spring Security 사용 시
        http.formLogin(f->f{
            f.loginProcessingUrl("/login");     // 로그인 url 설정
        });
         */

        // /user, /manager, /admin으로 들어가도 /loginForm으로 접근하도록
        return http.build();
    }