web-dev-qa-db-fra.com

Champ autowire impossible: private org.springframework.security.authentication.AuthenticationManager

J'essaie de créer un fournisseur de serveur OAuth2 à l'aide de ce tutoriel Spring OAuth2 . La principale différence entre l'exemple et mon projet - je n'utilise pas Spring Boot. J'essaie de scinder cette classe ( exemple de lien GitHub ) J'ai créé 2 classes:

@Configuration
@Order(-20)
@EnableResourceServer
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private AuthenticationManager authenticationManager;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.formLogin().loginPage("/login").permitAll()
            .and()
            .requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")
            .and()
            .authorizeRequests().anyRequest().authenticated();
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.parentAuthenticationManager(authenticationManager);
  }

}

Seconde classe:

@Configuration
@EnableAuthorizationServer
@EnableResourceServer
public class OAuth2AuthorizationConfiguration extends AuthorizationServerConfigurerAdapter {

  @Autowired
  private AuthenticationManager authenticationManager;

  @Bean
  public JwtAccessTokenConverter jwtAccessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    KeyPair keyPair = new KeyStoreKeyFactory(
            new ClassPathResource("keystore.jks"), "foobar".toCharArray())
            .getKeyPair("test");
    converter.setKeyPair(keyPair);
    return converter;
  }

  @Override
  public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
            .withClient("acme")
            .secret("acmesecret")
            .authorizedGrantTypes("authorization_code", "refresh_token",
                    "password").scopes("openid").autoApprove(true).accessTokenValiditySeconds(30);
}

  @Override
  public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(authenticationManager).accessTokenConverter(
            jwtAccessTokenConverter());
  }

  @Override
  public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess(
            "isAuthenticated()");
  }

}

Mais quand j'essaye de commencer ce code, je reçois:

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'OAuth2AuthorizationConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private   org.springframework.security.authentication.AuthenticationManager com.example.configuration.security.OAuth2AuthorizationConfiguration.authenticationManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] 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:5066)
at org.Apache.catalina.core.StandardContext.startInternal(StandardContext.Java:5584)
at org.Apache.catalina.util.LifecycleBase.start(LifecycleBase.Java:147)
at org.Apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.Java:899)
at org.Apache.catalina.core.ContainerBase.addChild(ContainerBase.Java:875)
at org.Apache.catalina.core.StandardHost.addChild(StandardHost.Java:652)
at org.Apache.catalina.startup.HostConfig.manageApp(HostConfig.Java:1863)
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.Apache.Tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.Java:301)
at com.Sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.Java:819)
at com.Sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.Java:801)
at org.Apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.Java:618)
at org.Apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.Java:565)
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.Apache.Tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.Java:301)
at com.Sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.Java:819)
at com.Sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.Java:801)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.Java:1468)
at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.Java:76)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.Java:1309)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.Java:1401)
at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.Java:829)
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 Sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.Java:324)
at Sun.rmi.transport.Transport$1.run(Transport.Java:200)
at Sun.rmi.transport.Transport$1.run(Transport.Java:197)
at Java.security.AccessController.doPrivileged(Native Method)
at Sun.rmi.transport.Transport.serviceCall(Transport.Java:196)
at Sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.Java:568)
at Sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.Java:826)
at Sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.Java:683)
at Java.security.AccessController.doPrivileged(Native Method)
at Sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.Java:682)
at Java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.Java:1142)
at Java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.Java:617)
at Java.lang.Thread.run(Thread.Java:745)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.authentication.AuthenticationManager com.example.configuration.security.OAuth2AuthorizationConfiguration.authenticationManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] 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)
... 58 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.authentication.AuthenticationManager] 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)
... 60 more

Je suppose que le problème est dans Spring Boot que je n'utilise pas dans mon application. J'ai essayé les solutions suivantes: First , Second J'utilise uniquement une configuration basée sur du code. Informations complémentaires: Java 8 Spring-security-oauth2 - 2.0.7.RELEASE, Spring-security-version - 4.0.1.RELEASE, Spring-version - 4.0. 6. LIBERATION. 

Comment le réparer?

METTRE À JOUR

J'ai crée 

@Configuration
public class AuthManager extends WebSecurityConfigurerAdapter {

    @Bean
    public AuthenticationManager customAuthenticationManager() throws Exception {
        return authenticationManager();
    }

}

Et maintenant j'ai une exception:

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.authentication.AuthenticationManager org.com.example.configuration.security.WebSecurityConfig.authenticationManager; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'customAuthenticationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
    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)
    ... 100 more
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'customAuthenticationManager': Requested bean is currently in creation: Is there an unresolvable circular reference?
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.beforeSingletonCreation(DefaultSingletonBeanRegistry.Java:335)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.Java:222)
    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.findAutowireCandidates(DefaultListableBeanFactory.Java:1017)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.Java:960)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.Java:858)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.Java:480)

Cette exception dans la classe OAuth2AuthorizationConfiguration.

16
Cat H

Créez une autre classe WebSecurityConfigurerAdapter qui sera la configuration "principale" et ajoutez le code suivant afin d'exposer un bean AuthenticationManager:

@Bean
public AuthenticationManager customAuthenticationManager() throws Exception {
  return authenticationManager();
}
21
a better oliver

Solution: il suffit de supprimer la méthode protected void configure(AuthenticationManagerBuilder auth). Selon javadoc, je n'ai pas besoin de cette méthode.

0
Cat H

Après avoir ajouté le bean, vous devez supprimer @Autowired de authenticationManager.

  private AuthenticationManager authenticationManager;
  @Bean
  public AuthenticationManager customAuthenticationManager() throws Exception {
      return authenticationManager();
  }
0