Spring Security: ошибка при создании bean-компонента с именем springsecurityfilterchain

Я пытаюсь подключить БД (MySQL) к Spring Security. Я хочу использовать стандартный способ проверки имени пользователя и полномочий из БД с помощью Spring Security. Я создал все необходимые таблицы (пользователи, авторитеты). Подключение к БД работает без Spring Security.

Когда я запускаю приложение, я получаю сообщение об ошибке сервера «ошибка создания bean-компонента с именем springsecurityfilterchain».

Я уже пытался перейти на JDK8, удалить «extends WebSecurityConfigurerAdapter» из моей конфигурации Spring Security, но это не работает.

Что мне нужно изменить или добавить?

Конфигурация Spring:

@Configuration
@ComponentScan("security")
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {
    @Bean
    public DataSource dataSource(){
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
            dataSource.setJdbcUrl(URL);
            dataSource.setUser(USERNAME);
            dataSource.setPassword(PASSWORD);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        return dataSource;
    } 

Инициализатор безопасности Spring:

public class SecurityInitializer
        extends AbstractSecurityWebApplicationInitializer {
    
}

Конфигурация безопасности Spring:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
    private final String[] ROLES = {"HR", "Manager", "Sales"};

    private final DataSource dataSource;

    @Autowired
    public SecurityConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource).withDefaultSchema();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/").hasAnyRole(ROLES)
                .antMatchers("/hr").hasAnyRole("HR")
                .and().formLogin().permitAll();
    }
}

Сервлет диспетчера Spring:

public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

Всегда включайте вся трассировка стека при ошибках Java.

chrylis -cautiouslyoptimistic- 30.03.2021 01:28
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
0
1
18
1

Ответы 1

это мой весенний класс безопасности, он работает, вы можете изменить его в зависимости от того, что вам нужно

 @Configuration
    @EnableWebSecurity
    public class SecurityConfig  extends WebSecurityConfigurerAdapter{
        @Autowired
        private PasswordEncoder passwordEncoder;
        @Autowired
        private DataSource dataSource ;
    
        private AuthenticationSuccessHandler authenticationSuccessHandler;
        
        @Autowired
        public SecurityConfig(AuthenticationSuccessHandler authenticationSuccessHandler) {
            this.authenticationSuccessHandler = authenticationSuccessHandler;
        }
        
        
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
         
            
            
            /*auth.inMemoryAuthentication().withUser("admin").password(bcpe.encode("1234")).roles("ADMIN","USER") ;  
            auth.inMemoryAuthentication().withUser("user").password(bcpe.encode("1234")).roles("USER") ;  
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) ;
        */
            PasswordEncoder bcpe=passwordEncoder() ;
    
         auth.jdbcAuthentication()
         .dataSource(dataSource) 
         .usersByUsernameQuery("select username as principal , password as credentials , active from users where username=?")
         .authoritiesByUsernameQuery("select username as principal, role as role from users where username=? ")
         .rolePrefix("ROLE_")
         .passwordEncoder(bcpe)  ;
        
        
        }
        
        
        @Override
        protected void configure(HttpSecurity http) throws Exception {
        
        http.formLogin().loginPage("/login").successHandler(authenticationSuccessHandler) ; 
        http.authorizeRequests().antMatchers("/admin/*").hasAnyRole("ADMIN") ;
        http.authorizeRequests().antMatchers("/user/*").hasAnyRole("CLIENT","ADMIN") ;
        http.authorizeRequests().antMatchers("/client/*").hasRole("CLIENT") ;
        http.exceptionHandling().accessDeniedPage("/403") ;
        http.logout()  
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/login")
        .invalidateHttpSession(true)
        .deleteCookies("JSESSIONID");   
        }
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }   
    }

Другие вопросы по теме