Arber Hoxha
Arber Hoxha

Reputation: 73

Spring boot @Autowired repository instance null when using spring security

My situation is this:

I am building a spring boot application, when I autowire the UserRepository in the controller it initializes it and when I try to call the findByUserName method everything is OK.

UserController

@Controller    
@RequestMapping(path="/api/v1/users") 
public class UserController {

@Autowired 
private UserRepository userRepository;

@GetMapping(path="/{userName}")
public @ResponseBody AuthenticationDetails getUserByUsername(@PathVariable String userName) throws UserNotFoundException {

    User user = userRepository.findByUserName(userName);=
    ...
    }
}

After creating the controller I needed to use Spring Security to secure the paths of the controller so I added in the SecurityConfig class the following configuration:

SecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable().authorizeRequests()
            .antMatchers(HttpMethod.POST, "/login").permitAll().anyRequest().authenticated().and()
            .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
                    UsernamePasswordAuthenticationFilter.class)
            .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

}
...
}

Now, when I try to post a request to the /login path I get a NullPointerException in the CustomAuthenticationProvider class when I try to load the data through userRepository instance by calling the findByUserName method because userRepository instance is null.

CustomAuthenticationProvider

public class CustomAuthenticationProvider implements AuthenticationProvider {

@Autowired 
private UserRepository userRepository;

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    User userFromRepository = userRepository.findByUserName(authentication.getName().toLowerCase()); 
    ...
}

My questions are this:

Is not the state of the beans the same during the run-time of the application? Are the beans created when the application loads right?

Why Spring Boot manages to autowire the instance with the bean in my controller and in the same application but in another class it does not autowire them?

Upvotes: 0

Views: 1696

Answers (1)

Leffchik
Leffchik

Reputation: 2030

The problem is that you create your CustomAuthenticationProvider like this new CustomAuthenticationProvider(), so it's not really a spring bean and it's fields can not be injected. What you need to do is define CustomAuthenticationProvider bean and it will work.

Upvotes: 2

Related Questions