'Spring Security cannot authenticate user although the user is exist in database

please help me with this, I'm new to spring security and I have been trying to logged in but Spring Security just don't let me access and I still can't figure. My CustomUserDetailsService still working and print out the account I intend to use to login

SecurityConfig

 @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private UserDetailsService userDetailsService;
    
        @Autowired
        BCryptPasswordEncoder passwordEncoder;
    
        @Bean
        @Override
        protected AuthenticationManager authenticationManager() throws Exception {
            // TODO Auto-generated method stub
            return super.authenticationManager();
        }
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder builder) throws Exception {
            builder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
        }
    
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/login", "/logout").permitAll()
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .defaultSuccessUrl("/admin", true)
                    .and()
                    .exceptionHandling().accessDeniedPage("/accessDenied");
        }
    
    
    }

CustomUserDetailsService

@Service("customUserDetailsService")
@Transactional
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findUsersByUsername(username);

        if (user == null) {
            log.error("User not found");
            throw new UsernameNotFoundException("User not found");
        } else {
            log.info("User found in the dbs", username);
            System.out.println(user.getUsername());
            System.out.println(user.getPassword());
        }
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        //looping all roles from user -> for each role, create a new simpleGranted
        //auth by passing the role name
        for (Role role : user.getRoles()) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        //return spring sec user (core userDetail)
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
    }
}

User

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "user",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "username"),
                @UniqueConstraint(columnNames = "email")
        })
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @NotBlank(message = "Username is required")
    private String username;
    @NotBlank(message = "Password is required")
    private String password;
    @Email
    @NotBlank(message = "Email is required")
    private String email;
    private Instant created;
    private boolean enabled;
    //load all the roles whenever load an user
    @ManyToMany(fetch = FetchType.EAGER)
    private Collection<Role> roles = new ArrayList<>();



}

Everytime I logged in with the right account, Spring Security always give me "Bad Credentials" enter image description here

Edited: username and password (both passwords are 123) enter image description here



Solution 1:[1]

It isn't working because you didn't specify the implementation of the UserDetailsService.So what spring is actually doing is, It is using the default username(user) and the random password(generated at runtime) as the required credentials. To make spring use your custom user details, please replace This:

@Autowired
private UserDetailsService userDetailsService;

With that:

@Autowired
@Qualifier("customUserDetailsService")
private UserDetailsService userDetailsService;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1