I am just learning Spring Security. My goal is to authenticate the user by their username and password, which are stored in PostgreSQL.
So far, this is what I have:
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class configurator {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests(auth ->
auth
.anyRequest().authenticated()
)
.httpBasic();
return http.build();
}
}
public class CustomUserDetails implements UserDetails {
private final User user;
public CustomUserDetails(User user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
public class CustomUserDetailService implements UserDetailsService {
private final UserRepository userRepository;
public CustomUserDetailService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
return new CustomUserDetails(user);
}
}
You may also find this code on https://github.com/RezaS/Login-with-Spring-Security.
My question is, what do I do with CustomUserDetailService
now? Should it be implemented in Configurator
class? If so, how do I do this?
CodePudding user response:
CustomUserDetailService must be annotate @Service or @Component for register to spring bean context.
Also you can read more about UserDetailsService: https://howtodoinjava.com/spring-security/inmemory-jdbc-userdetails-service/