Spring Boot中管理员和用户的两个不同的登录页面

问题描述 投票:0回答:1

我需要带有多个客户和管理员登录页面的 Spring Boot 应用程序。我写了两个authenticationManager,一个用于客户,另一个用于管理员。请参阅配置类:

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 类:

AdminAuthtenticationSecurity.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.BeanInstantiationException:无法实例化[org.springframework.security.authentication.AuthenticationManager]:工厂方法“customerAuthenticationManager”抛出异常并显示消息:找到类型接口org.springframework.security.authentication.AuthenticationManager的2个bean,但没有一个被标记为主要

如何解决这个错误?

谢谢。

java spring-boot authentication spring-security jwt
1个回答
0
投票

您可以添加

@Primary
注释来将 AuthenticationManager bean 之一标记为主。当有多个选项可用于注入时,这会告诉 Spring 使用哪个 bean。

customerSecurityConfig.class:

@Configuration 
@Order(2) 
public class customerSecurityConfig {

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

    //...
}

通过将

@Primary
添加到
customerAuthenticationManager
类中的
customerSecurityConfig
方法,您可以向 Spring 指示,当有多个 bean 可用于
AuthenticationManager
时,该 bean 是主 bean。

© www.soinside.com 2019 - 2024. All rights reserved.