Я пытаюсь подключить БД (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[]{"/"};
}




это мой весенний класс безопасности, он работает, вы можете изменить его в зависимости от того, что вам нужно
@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();
}
}
Всегда включайте вся трассировка стека при ошибках Java.