在AuthenticationProvider中没有找到类型的限定bean以用于依赖

时间:2014-09-10 13:29:03

标签: java spring spring-mvc jpa spring-security

嗨我正在尝试自定义AuthenticationProvider,但我正在使用autowire注释进行折磨。我有一个类在我的数据库中找到用户,然后使用LDAP服务器对它们进行身份验证,我有逻辑,但我无法通过此autowire错误。

这是实现WebSecurityConfigurerAdapter

的类
package com.abc.config;
@Configuration
@EnableWebMvcSecurity
@ComponentScan(basePackages = {"com.abc.auth"}) 
public class ConfigSecurity extends WebSecurityConfigurerAdapter {




    @Autowired 
    private AuthProvider authent; <--- this is the autowire that gives me troubles

    @Override
    protected void configure( HttpSecurity http ) throws Exception 
    {
        http
            .authenticationProvider(authent)
            .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
            .formLogin()
                    .loginPage("/prueba")
                    .permitAll()
                    .and()
            .logout()                                    
                    .permitAll();
    }
}

这是我的JPA配置类

package com.abc.config;
@Configuration
@EnableSpringConfigured
@ComponentScan( basePackages = {"com.abc.dom", "com.abc.repo", "com.abc.auth"})
@EnableJpaRepositories(basePackages="com.abc.repo")
public class ConfigJPA 
{

       @Bean
       public LocalContainerEntityManagerFactoryBean entityManagerFactory() 
               throws ClassNotFoundException 
       {

          LocalContainerEntityManagerFactoryBean em  = 
                  new LocalContainerEntityManagerFactoryBean();

          em.setDataSource( dataSource() );
          em.setPackagesToScan("com.abc.dom");
          em.setPersistenceProviderClass(HibernatePersistence.class);
          em.setJpaProperties( asignProperties() );

          return em;
       }

       //Propiedades Hibernate
       Properties asignProperties() {

           Properties jpaProperties = new Properties();

           jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect");
           jpaProperties.put("hibernate.format_sql", true);
           jpaProperties.put("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
           jpaProperties.put("hibernate.show_sql", false);

           return jpaProperties;
       }


       @Bean
       public DataSource dataSource(){

          DriverManagerDataSource dataSource = 
                  new DriverManagerDataSource();

          dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
          dataSource.setUrl("jdbc:oracle:thin:@127.0.0.1:1521:XE");
          dataSource.setUsername("theUser");
          dataSource.setPassword("myPasswordToAskQuestions");

          return dataSource;
       }

       @Bean
       public JpaTransactionManager transactionManager() 
               throws ClassNotFoundException 
       {

            JpaTransactionManager transactionManager = 
                    new JpaTransactionManager();

            transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());

            return transactionManager;
        }

}   

和我的班级,我有我的验证方法

package com.abc.auth;
public class AuthProvider implements AuthenticationProvider 
{

    @Autowired
    private UserRepo Repository_user;



    public Authentication authenticate(Authentication authentication) 
            throws AuthenticationException {

    UserClass user = null;
    Authentication auth = null;
    String name = null;
    String password = null;

    try 
    {
        name = authentication.getName();
        password = authentication.getCredentials().toString();

        if( name != null  &&  
            !name.trim().equals("")  &&  
            password != null  && 
            !password.trim().equals("") )
        {
            user = this.findUserInTheDB(name); //this method returns a User

            if(user != null)
            {
                if( authUserLDAP(user .getLdapServer().getDirection(), 
                                         user .getLdapServer().getDom(), 
                                         name, password, true) ) <-- this method authenticate a user with LDAP
                {
                    List<GrantedAuthority> grantedAuths  =  new ArrayList();
                    grantedAuths.add(new SimpleGrantedAuthority(usuario.getRole().getName()));
                    auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
                }
                else
                {
                     throw new BadCredentialsException("invalid credentials");
                }
            }
            else
            {
                throw new UsernameNotFoundException("the user dont exist");
            }

        }
        else
        {
            throw new BadCredentialsException("invalid credentials");
        }
    } 
    catch (AuthenticationException e) {
        throw e;
    }
    catch (Exception ex) {
        throw new AuthenticationServiceException("", ex.getCause());
    }

    return auth;
    }

    private UserClass findUserInTheDB(String login) 
{
    UserClass user  =  null;

    if(login  !=  null && !login.trim().equalsIgnoreCase(""))
    {
        user  =  Repository_user.findByLogin(login);
    }

    return user  ;
}





    public boolean supports(Class<?> arg0) {
         return arg0.equals(UsernamePasswordAuthenticationToken.class);
    }

    private boolean authUserLDAP(String server, String dom, String login, 
                                      String password, boolean dev) 
{
    String INITCTX = "com.sun.jndi.ldap.LdapCtxFactory";
    Hashtable<String, String> env = new Hashtable<String, String>();

    //para propositos de prueba en desarrollo
    if(dev)return true;

    try
    {
        env.put(Context.INITIAL_CONTEXT_FACTORY, INITCTX);
        env.put(Context.PROVIDER_URL, "ldap://" + server);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.SECURITY_PRINCIPAL, login + dominio);  

        DirContext ctx = new InitialDirContext(env);
    } 
    catch (Exception e) 
    {

        return false; 
    }

    return true; 
}

public void setRepositoryUser(UserRepo userRepo ) {
        this.Repository_user= userRepo ;
    }


}

UserRepo类

package com.abc.repo;
public interface UserRepo extends JpaRepository <UserClass, Long> {

    public UserClass findByLogin(String login);
}

这是控制台输出

INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Wed Sep 10 08:09:19 VET 2014]; root of context hierarchy
INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Registering annotated classes: [class com.abc.config.ConfigSecurity]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
ERROR: org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configSecurity': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.abc.auth.AuthProvider com.abc.config.ConfigSecurity.authent; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.abc.auth.AuthProvider] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4971)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:670)
    at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1839)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.abc.auth.AuthProvider com.abc.config.ConfigSecurity.authent; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.abc.auth.AuthProvider] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    ... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.abc.auth.AuthProvider] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480)
    ... 28 more

0 个答案:

没有答案