简体   繁体   中英

Spring boot security using custom provider

My requirement is to implement security using Spring boot. I have configured the configuration file as below:-

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Bean
    public CustomUserDetailsDao userDao(){
       return new CustomUserDetailsDao(profileData());
    }


    @Bean
    public ProfileData profileData(){
       return  new XStreamProfileData();
    }
    /*  
    @Autowired
    Environment env;

    @Bean
    public DataSource dataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url(env.getProperty()dbUrl);
        dataSourceBuilder.username(username);
        dataSourceBuilder.password(password);
        return dataSourceBuilder.build();
    }*/


    @Bean
    public CustomDaoAuthenticationProvider authProvider() {
       CustomDaoAuthenticationProvider provider = new CustomDaoAuthenticationProvider();
        // setters inside provider goes here
         provider.setUserDetailsService(userDao());
        return provider;
    }



    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/", "/home")
                .permitAll()
                .antMatchers("/admin")
                .hasRole("ADMIN")
                .anyRequest().authenticated().and()
                .formLogin().permitAll()
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler);


    }

    @Autowired
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider());
    }
}

Here I am trying to autowire CustomDaoAuthenticationProvider from an already implemented project which is packaged as jar and deployed. I have added this jar as a dependency in my pom.xml

The skelteon of CustomDaoAuthenticationProvider in the spring jar, goes like this:-

public class CustomDaoAuthenticationProvider extends DaoAuthenticationProvider {
    public CustomDaoAuthenticationProvider() {
            super();

        }
         @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        //Code for User authentication goes here
        }
    }

Please note that the class is not annotated with @Component.

On running the spring boot app, after injecting all the beans that was required for the custom provider, I get an error:-

Caused by: java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
        at org.springframework.jdbc.core.support.JdbcDaoSupport.checkDaoConfig(JdbcDaoSupport.java:111)
        at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDao' defined in class path resource : Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.obtainBeanInstanceFromFactory(ConfigurationClassEnhancer.java:389)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
        at com.security.myapp.springsecuritymyapp.config.SecurityConfiguration$$EnhancerBySpringCGLIB$82E.userDao(<generated>)
        at com.security.myapp.springsecuritymyapp.config.SecurityConfiguration.authProvider(SecurityConfiguration.java:43)
        at com.security.myapp.springsecuritymyapp.config.SecurityConfiguration$$EnhancerBySpringCGLIB$$87f94c8.(<generated>)
        at com.security.myapp.springsecuritymyapp.config.SecurityConfiguration$$EnhancerBySpringc.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
        at com.security.myapp.springsecuritymyapp.config.SecurityConfiguration$$EnhancerBySpringCGLIB$$87f094c8.authProvider(<generated>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.obtainBeanInstanceFromFactory(ConfigurationClassEnhancer.java:389)
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
        at com.security.myapp.springsecuritymyapp.config.SecurityConfiguration$$EnhancerBySpringCGLIB.authProvider(<generated>)
        at com.security.myapp.springsecuritymyapp.config.SecurityConfiguration.configure(SecurityConfiguration.java:94)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Please help me out to resove the above error

Since you are using DaoAuthenticationProvider you have to have a dataSource as a bean.

For datasource to work you must add the following dependency.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

Added to the above you also have to add the JDBC driver dependency.

For example for MySql the following is the dependency.

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
</dependency>

And in application properties you have to configure the JDBC properties as follows (MySql example)

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

According to the log the error is coming from the userDao bean creation because it has no datasource or jdbcTempalte assigned.

BeanCreationException: Error creating bean with name 'userDao' defined in
class path resource : Invocation of init method failed; nested exception is 
java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is 
required

Assuming that all the spring.datasource are set on your application.properties then make sure that CustomUserDetailsDao has injected the DataSource bean, like this

@Bean
public CustomUserDetailsDao userDao(DataSource datasoruce){
   CustomUserDetailsDao myUserDao = new CustomUserDetailsDao(profileData());
   myUserDao.setDataSource(datasource);
   return myUserDao;
}

application.properties for h2 database

spring.datasource.url:jdbc:h2:~/test2
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

Here is an example Dao Implementation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM