Hi I have a problem with Spring Security confgiuration within my Spring MVC project.
I have configured the SecurityConfig class where there is the configuration of the various AuthenticationManager and AtuhenticationProvider (I use a DaoAuthenticationProvider but it is not important)
I don't understand why when I start the application the filter doesn't work. The application works but it seems that the Servlet dispatcher does not consider the configuration. I also add the configuration class to the getRootConfigClasses method.
I just don't understand why it doesn't work....? Can anyone help me out?
AppInitializer class that implement AbstractAnnotationConfigDispatcherServletInitializer
@Configuration
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppContext.class, SecurityConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebMvcConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
WebMvcConfig class that implement WebMvcConfigurer
@Configuration
@ComponentScan(basePackages = { "com.einaudi.lwe" })
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer{
@Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}
AppContext for configure repository Bean to communicate with Db
@Configuration
@ComponentScan(basePackages = { "com.einaudi.lwe" })
@EnableTransactionManagement(proxyTargetClass = true)
@PropertySource("classpath:database.properties")
public class AppContext {
@Autowired
private Environment environment;
@Bean
public LocalSessionFactoryBean sessionFactory() {
//Oggetto che server a Hibernate per settare proprietà del ORM
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan(new String[] { "com.einaudi.lwe.data.entity" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
@Bean
public DataSource dataSource() {
//Oggetti provenienti da spring per settare i jdbc
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
return properties;
}
@Bean
public HibernateTransactionManager getTransactionManager() {
//Oggetto di transaction manager di Hibenate (Il transaction manager è quell'oggetto necessario alla gestione delle transazioni tra un applicativo e un DBMS)
//Le transazioni sono operazioni attue al garantire delle proprietà di consistenza dei dati.
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
SecurityConfig class that implement WebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private LweUserService lweUserService;
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider(){
DaoAuthenticationProvider provider =
new DaoAuthenticationProvider();
provider.setPasswordEncoder(encoder());
provider.setUserDetailsService(lweUserService);
return provider;
}
@Bean
public static PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/student/**").hasRole("STUDENT")
.antMatchers("/instructor/**").hasRole("INSTRUCTOR")
.antMatchers("/**").permitAll()
.and()
.formLogin()
.loginPage("/loginUser")
.loginProcessingUrl("/user_login")
.failureUrl("/loginUser?error=loginError")
.defaultSuccessUrl("/userPage")
.and()
.logout()
.logoutUrl("/user_logout")
.logoutSuccessUrl("/protectedLinks")
.deleteCookies("JSESSIONID")
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and()
.csrf().disable();
}
}
I use tomcat 8.5.78
CodePudding user response:
try removing the @configuration from the AppInitializer class
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppContext.class, SecurityConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebMvcConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
refer this for detail information click here
CodePudding user response:
I suggest you to use application.properties
file under resources folder for establishing DB connection. Further instead of using WebMvcConfig class you can just give @EnableWebMvc
annotation in SecurityConfig class. It should work as because the spring boot will automatically set the prefix and postfix and maps to the available view page. This had worked for my project.