Dmitriy Tarasov
Dmitriy Tarasov

Reputation: 1969

Autowired CrudRepository into UserDetailsService is always null

I'm newbie in Spring-World, I have a Spring Boot application with Spring Security and JPA. Also have CrudRepository and UserDetailsService, see below

Application class

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

UserDao

@Repository
public interface UserDao extends CrudRepository<User, Long> {
    public Collection<User> findByName(String name);
}

ApiUserDetailsService

@Component
public class ApiUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao dao;

    @Override
    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
        assert dao != null;
        ...
    }
}

Security Config

@Configuration
@EnableWebSecurity
public class HttpBasicAuthConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.requestCache().requestCache(new NullRequestCache());
        http.httpBasic();
        http.authorizeRequests().anyRequest().authenticated();
    }


    @Autowired
    public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(new ApiUserDetailsService());
    }
}

Why Autowired dao is always null? What I do wrong?

Upvotes: 3

Views: 4009

Answers (1)

Ricardo Veguilla
Ricardo Veguilla

Reputation: 3155

You are creating the ApiUserDetailsService manually, in the the method:

@Autowired
public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(new ApiUserDetailsService());
}

What you want is:

@Configuration
@EnableWebSecurity
@EnableJpaRepositories(basePackages = {"your.package.dao"})
public class HttpBasicAuthConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.requestCache().requestCache(new NullRequestCache());
        http.httpBasic();
        http.authorizeRequests().anyRequest().authenticated();
    }

    // register ApiUserDetailsService as a bean  
    @Bean 
    public UserDetailsService apiUserDetailsService() {
        return new ApiUserDetailsService();      
    } 

    @Autowired
    public void registerAuthentication(AuthenticationManagerBuilder auth) throws     Exception {
        // get the autowired bean from Spring
        auth.userDetailsService(apiUserDetailsService());
    }
}

Upvotes: 9

Related Questions