Весенняя загрузка: DelegateBuilder не может быть пустым при автоматической аутентификации проводов в пользовательском UserDetailsService - PullRequest
0 голосов
/ 19 декабря 2018

Привет, я новичок в весенней загрузке и пытаюсь внедрить систему безопасности для моего остальных API.

Я использую весеннюю загрузку 2.0.7. Выпуск

У меня настроен мой WebSecurityConfig какследующие

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource(name = "userService")
    private UserDetailsService userDetailsService;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
    }

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
            .passwordEncoder(encoder());
    }

    @Bean
    public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
        return new JwtAuthenticationFilter();
    }
    @Bean
    public PasswordEncoder encoder(){
         PasswordEncoder encoder = new CustomPasswordEncoder(); 
         return encoder;
    }
    ....
   }

Я добавил имя ресурса, чтобы я мог указать пользовательский userDetailsService.

Я попытался настроить Bean-компонент authenticationManager, указав и указав компонент с помощью компонента Qualifier authenticationManager, по-прежнемуошибка остается прежней.

мой pom.xml выглядит для безопасности

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

, а мой реализованный UserServiceImpl равен

@Service(value = "userService")
public class UserServiceImpl implements UserService, UserDetailsService {

    @Autowired
    private UserDAOService userDao;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
         User user = userDao.findByUsername(username);
         if(user == null){
             throw new UsernameNotFoundException("Invalid username or password.");
          }
         return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), getAuthority());
    }

    @Override
    public String login(LoginUser user) {
           // valid user if it exits then do the following

            authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));

           //generate the token and do other process.
    }

. Ниже приведены журналы ошибок.я предоставил только почтовые ошибки

  Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource [com/saikrishna/security/config/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
  Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService': Unsatisfied dependency expressed through field 'authenticationManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource [com/saikrishna/security/config/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
  Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.authenticationManager' defined in class path resource [com/saikrishna/security/config/WebSecurityConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
  Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.authentication.AuthenticationManager]: Circular reference involving containing bean 'webSecurityConfig' - consider declaring the factory method as static for independence from its containing instance. Factory method 'authenticationManagerBean' threw exception; nested exception is java.lang.IllegalArgumentException: delegateBuilder cannot be null
  Caused by: java.lang.IllegalArgumentException: delegateBuilder cannot be null
  at org.springframework.util.Assert.notNull(Assert.java:193) ~[spring-core-5.0.11.RELEASE.jar:5.0.11.RELEASE]

1 Ответ

0 голосов
/ 19 декабря 2018

Чтобы помочь вам лучше, лучше указать, какую ссылку вы используете для реализации механизма JWT.

Концептуально эта часть исходного кода неверна:

@Override
public String login(LoginUser user) {
       // valid user if it exits then do the following

        authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));

       //generate the token and do other process.
}

Посмотрите, могут ли следующие изменения помочь вам

1) Рассмотреть возможность использования Java Config для объявления ваших компонентов в отдельном классе конфигурации

@Configuration
public class ServiceConfig{   
   @Bean
   protected UserDAOService daoService()
   {
      return new UserDAOServiceImpl();
   }
   @Bean
   protected UserDetailsService userDetailService( UserDAOService dao )
   {
      return new UserServiceImpl( dao );
   }
   @Bean
   public PasswordEncoder encoder(){
     PasswordEncoder encoder = new CustomPasswordEncoder(); 
     return encoder;
   }
   @Bean
   public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception{                           {
    return new JwtAuthenticationFilter();
   }
}

2) Модификация вашего WebSecurityConfig

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    protected void configure( AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService( userDetailsService ).passwordEncoder( passwordEncoder );
    }

}
...