代码之家  ›  专栏  ›  技术社区  ›  Ali Rahimi

春季启动中Admin和User的两个不同登录页面

  •  0
  • Ali Rahimi  · 技术社区  · 2 年前

    我需要春季启动应用程序与多个登录页面的客户和管理员。我写了两个authenticationManager,一个用于客户,另一个用于管理员。请参阅configs类:

    customerSecurityConfig.class

    @Configuration 
    @Order(2) 
    public class customerSecurityConfig {
    
    @Bean
    public AuthenticationManager customerAuthenticationManager(AuthenticationConfiguration customerConfig) throws Exception {
        return customerConfig.getAuthenticationManager();
    }
    
    //...
    
    }
    

    adminSecurityConfig.class

    @Configuration
    @Order(2)
    public class adminSecurityConfig {
    
        @Bean
        public AuthenticationManager adminAuthenticationManager(AuthenticationConfiguration config) throws Exception {
            return config.getAuthenticationManager();
        }
    
       //...
    
    }
    

    以及针对客户和管理员的AuthenticationService类:

    AdminAuthentificationSecurity.class:

    @Server
    @RequiredArgsConstructor
    public class AdminAuthenticationService {
       
        @Qualifier("adminAuthenticationManager")
        private final AuthenticationManager adminAuthenticationManager;
    
        public AuthenticationResponse register() {
    
            //...        
    
        }
    
        public AuthenticationResponse authenticate () {
    
           //...
    
    
        }
        
    }
    

    CustomerAuthenticationSecurity.class

    @Service
    @RequiredArgsConstructor
    public class CustomerAuthenticationService {
     
      @Qualifier("customerAuthenticationManager")
      private final AuthenticationManager customerAuthenticationManager;
    
      public AuthenticationResponse register() {
        
        //...
       
      }
    
      public AuthenticationResponse authenticate() {
        //...
      }
    
    }
    

    这是日志的错误:

    org.springframework.beans。BeanInstanceException:未能实例化[org.springframework.security.AuthenticationManager]:工厂方法“customerAuthenticationManager”引发异常,消息为:为类型接口org.springfframework.security.authentication找到2个bean。AuthenticationManager,但没有标记为主要

    如何解决这个错误?

    谢谢

    1 回复  |  直到 2 年前
        1
  •  1
  •   WiseHipoppotamus    2 年前

    您可以添加 @Primary 注释以标记其中一个 AuthenticationManager 以豆类为主。当有多个选项可供注入时,这条消息会告诉Spring要使用哪个bean。

    customerSecurityConfig.class:

    @Configuration 
    @Order(2) 
    public class customerSecurityConfig {
    
        @Bean
        @Primary // <-------
        public AuthenticationManager customerAuthenticationManager(AuthenticationConfiguration customerConfig) throws Exception {
            return customerConfig.getAuthenticationManager();
        }
    
        //...
    }
    

    通过添加 主要的,重要的 customerAuthenticationManager 中的方法 customerSecurityConfig 类,当有多个bean可用于时,您向Spring指示该bean是主bean AuthenticationManager .