2014-11-20 6 views
1

У меня есть следующая конфигурация:пружинные круговые зависимости

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled=true) 
public class SecurityConfig { 
    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityConfig.class); 
    @Resource 
    private UserDetailsService userDetailsService; 
    @Resource 
    private PasswordEncoder passwordEncoder; 

    ..... 

    @Configuration 
    @Order(2) 
    public static class MobileApiSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { 
     @Resource 
     private UserDetailsService userDetailsService; 
     @Resource 
     private PasswordEncoder passwordEncoder; 
     @Autowired 
     private CustomBasicAuthenticationFilter customBasicAuthenticationFilter; 
     @Autowired 
     private TokenSecurityFilter tokenSecurityFilter; 

     protected void configure(AuthenticationManagerBuilder auth) throws Exception { 

      auth 
      .userDetailsService(userDetailsService) 
      .passwordEncoder(passwordEncoder); 

     } 

     protected void configure(HttpSecurity http) throws Exception { 
      http 
       .addFilter(customBasicAuthenticationFilter) 
       .addFilterBefore(tokenSecurityFilter, CustomBasicAuthenticationFilter.class) 
       .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() 
        .csrf().disable() 
       .authorizeRequests()   
        .antMatchers(Mappings.MOBILE_API + "/**").hasAnyRole(Globals.MOBILE_API_USER_ROLE) 
        .and() 
       .exceptionHandling() 
        .authenticationEntryPoint(new CustomBasicAuthenticationEntryPoint()) 
        .and() 
       .requestCache() 
        .requestCache(new NullRequestCache()); 
     } 

    } 

Это мой пользовательский фильтр:

@Component 
public class CustomBasicAuthenticationFilter extends BasicAuthenticationFilter { 
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomBasicAuthenticationFilter.class); 
    @Autowired 
    private PrincipalRepository principalRepository; 
    @Autowired 
    private AuthenticationCache authenticationCache; 

    @Autowired 
    public CustomBasicAuthenticationFilter(AuthenticationManager authenticationManager) { 
     super(authenticationManager); 
    } 

    @Override 
    protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, 
      Authentication authResult) throws IOException { 
     Principal principal = principalRepository.findOne(PrincipalPredicates.userNameEquals(authResult.getName())); 

     if (principal != null) { 
      principal.setLastLoginTime(DateTime.now()); 
      principalRepository.save(principal); 
     } else { 
      LOGGER.error("Unable to retrieve user " + authResult.getName()); 
     } 

     authenticationCache.add(authResult, request, response); 

     super.onSuccessfulAuthentication(request, response, authResult); 
    } 
} 

Но, при попытке развернуть на Tomcat, следующее исключение:

Error creating bean with name 'customBasicAuthenticationFilter' defined in file [C:\work\...]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.security.authentication.AuthenticationManager]: : 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: {}; 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: {} 

Я не уверен, почему мой фильтр ищет аутентификационный менеджер, так как я его автоустанавливаю. Помощь приветствуется.

Обновлено Вопрос: Я добавил этот код, чтобы решить проблему AuthenticationManager:

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

Добавляя выше, я могу пройти мимо вопроса AuthenticationManager, но теперь я получаю этот вопрос:

org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: private CustomBasicAuthenticationFilter SecurityConfig$MobileApiSecurityConfigurerAdapter.customBasicAuthenticationFilter; 
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: 
Error creating bean with name 'customBasicAuthenticationFilter': 
Requested bean is currently in creation: Is there an unresolvable circular reference? 

Благодаря

+0

Вы автоматически подключили боб с помощью конструктора. Где вы указываете фабрике компонентов, как создать экземпляр AuthenticationManager для перехода к конструктору? Вот о чем он жалуется. Автоматическая проводка зависимостей конструктора недостаточна; вам также нужно создать компонент для ссылки. – duffymo

+0

Спасибо за комментарий. Я думаю, что понимаю эту проблему, но я просто не знаю, как ее исправить. Благодарю. – Jim

ответ

0

Вы можете попробовать добавить @EnableWebSecurity аннотацию на вершине определения класса MobileApiSecurityConfigurerAdapter.

0

Я добавил аннотацию @Lazy к фильтру, и теперь я могу ее развернуть.

Не стесняйтесь предлагать другие решения.

Смежные вопросы