2017-01-31 44 views
0

我想爲我的REST API製作BasicAuth,這是我的問題。不能autowire Spring安全實施類

AccountConfiguration

// Spring Security uses accounts from our database 
@Configuration 
public class AccountConfiguration extends GlobalAuthenticationConfigurerAdapter { 

    private UserAuthService userAuthService; 

    @Autowired 
    public AccountConfiguration(UserAuthService userAuthService) { 
     this.userAuthService = userAuthService; 
    } 

    @Override 
    public void init(AuthenticationManagerBuilder auth) throws Exception { 
     auth.userDetailsService(userAuthService); 
    } 
} 

在構造函數中的IntelliJ告訴我

無法自動裝配。的「UserAuthService型無豆中

,但我有相同的包的豆,那就是:

@Service 
@Transactional 
public class UserAuthService implements UserDetailsService { 

    private UserRepository userRepository; 

    @Autowired 
    public UserAuthService(UserRepository userRepository) { 
     this.userRepository = userRepository; 
    } 

    @Override 
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 
     User user = userRepository.findByUsername(username); 

     if (user == null) { 
      throw new UsernameNotFoundException("Could not find the user: " + username); 
     } 

     return new org.springframework.security.core.userdetails.User(
       user.getUsername(), 
       user.getPassword(), 
       true, 
       true, 
       true, 
       true, 
       AuthorityUtils.createAuthorityList("USER")); 
    } 
} 

這裏是Spring Security的我的第三個配置文件:

@EnableWebSecurity 
@Configuration 
public class WebConfiguration extends WebSecurityConfigurerAdapter{ 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     // allow everyone to register an account; /console is just for testing 
     http 
      .authorizeRequests() 
       .antMatchers("/register", "/console/**").permitAll(); 

     http 
      .authorizeRequests() 
       .anyRequest().fullyAuthenticated(); 

     // making H2 console working 
     http 
      .headers() 
       .frameOptions().disable(); 

     /* 
     https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#when-to-use-csrf-protection 
     for non-browser APIs there is no need to use csrf protection 
     */ 
     http 
      .csrf().disable(); 
    } 
} 

那麼我該如何解決這個問題?這裏有什麼問題?爲什麼它不能自動裝配UserAuthService

+1

除了智能感知的IntelliJ錯誤。當您嘗試運行代碼時會得到什麼錯誤?有時候,intellij錯了。 –

+0

我沒有得到任何錯誤,但我的整個身份驗證只是不起作用,我認爲這只是正因爲如此。我不知道我是否可以編輯這篇文章,提供關於我的身份驗證的更多詳細信息,而不是編輯或我應該創建一個新的。 – doublemc

+1

我解決了我的其他問題,這似乎只是IntelliJ錯誤,謝謝。 – doublemc

回答

1

嘗試更改代碼注入接口,而不是實現。這是一個交易代理。

private UserDetailsService userAuthService; 

@Autowired 
public AccountConfiguration(UserDetailsService userAuthService) { 
    this.userAuthService = userAuthService; 
} 

Spring Autowiring class vs. interface?

+0

仍然不起作用,現在只是說「不能autowire。沒有發現」UserAuthService類型的豆「 – doublemc

+1

它是'UserDetailsS​​ervice'而不是'UserAuthService'。確保你做了正確的改變(2次更改)。同時,發佈錯誤爲了更好的理解stacktrace。 –