Search code examples
javaspringspring-bootspring-securityjavabeans

Can I add a priority to execute method level @Bean?


In my test application I have my security configuration class as follows.

package myProject.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@SuppressWarnings("deprecation")
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userService;

    @Override
    public void configure(HttpSecurity theHttp) throws Exception {
        theHttp.authorizeRequests()
                .antMatchers("/design", "/order")
                    .access("hasRole('ROLE_USER')")
                .antMatchers("/", "/**")
                    .access("permitAll")
                .and()
                .formLogin()
                    .loginPage("/login")
                    .defaultSuccessUrl("/", true) 
                .and()
                .logout()
                    .logoutSuccessUrl("/login")
                .and()
                .csrf()
                    .ignoringAntMatchers("/h2-console/**")
                .and()
                .headers()
                    .frameOptions()
                    .sameOrigin();
    }

    @Bean
    public PasswordEncoder encoder() {
        return new StandardPasswordEncoder("53cr3t");
    }

    @Override
    public void configure(AuthenticationManagerBuilder theAuth) throws Exception {
        theAuth.userDetailsService(userService)
                .passwordEncoder(encoder());
    }

}

There I defined encoder() and annotated it as @Bean. That means the method produces a bean to be managed by the spring container. Again I have the need to access the encoder via a constructor as shown below.

package myProject.security;

import org.springframework.context.annotation.DependsOn;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import myProject.data.UserRepository;

@Controller
@RequestMapping("/register")
public class RegistrationController {

    private final UserRepository userRepo;
    private final PasswordEncoder passwordEncoder;

    public RegistrationController(UserRepository theUserRepo, PasswordEncoder thePasswordEncoder) {
        this.userRepo = theUserRepo;
        this.passwordEncoder = thePasswordEncoder;
    }

    @GetMapping
    public String registrationForm() {
        return "userRegistry";
    }

    @PostMapping
    public String processRegistration(RegistrationForm theUserRegistration) {
        userRepo.save(theUserRegistration.tranformUser(passwordEncoder));
        return "redirect:/loginPage";
    }

}

User repository class

package myProject.data;
import org.springframework.data.repository.CrudRepository;
import myProject.User;

public interface UserRepository extends CrudRepository<User, Long> {

  User findByUsername(String theUsername);
  
}

User details service implementation

package myProject.security;

import org.jvnet.hk2.annotations.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import myProject.User;
import myProject.data.UserRepository;

@Service
public class UserRepositoryDetailsService implements UserDetailsService {

    private final UserRepository userRepo;

    @Autowired
    public UserRepositoryUserDetailsService(UserRepository theUserRepository) {
        this.userRepo = theUserRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String theUsername) throws UsernameNotFoundException {
        User user = userRepo.findByUsername(theUsername);
        if (user != null) {
            return user;
        }
        throw new UsernameNotFoundException("User " + theUsername + " not found");
    }

}

In the above example I am using the password encoder as constructor argument. The problem is that @Bean method is not executed by the time constructor of the RegistrationController is called. I could overcome this issue after adding the encoder() to the bootstrap class but I don't think that is a solution.

How can I solve my issue?

Error - Error creating bean with name 'registrationController' defined in file [C:\Users\TECH WORLD\IdeaProjects\Project\target\classes\myProject\security\RegistrationController.class]: 
Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 
'securityConfig': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with 
name 'inMemoryUserDetailsManager' defined in class path resource [org/springframework/boot/autoconfigure/security/servlet/UserDetailsServiceAutoConfiguration.class]: Bean instantiation 
via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [
org.springframework.security.provisioning.InMemoryUserDetailsManager]: Factory method 'inMemoryUserDetailsManager' threw exception; 
nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'passwordEncoder': 

Requested bean is currently in creation: Is there an unresolvable circular reference?


Solution

  • In-fact my problem solved after adding @Lazy annotation to the constructor argument it has few more issues when proceeding further. I found the real fault. The fault is in UserRepositoryDetailsService class. It is annotated as @Service but in my code the service in imported by import org.jvnet.hk2.annotations.Service;. However it should be imported from import org.springframework.stereotype.Service;. Once I did fix it all other issues solved.