I need a login strategy to work with a mysql db. My user table has md5 password encryption. I need to develop login. My code won't work. Here is my SecutiryConfig:
@Configuration
@EnableWebSecurity
@EnableGlobalAuthentication
@ComponentScan("org.ebook.*")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
Environment env;
@Autowired
private UserRepository userRepository;
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(new UserService(userRepository)).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").hasAnyRole("USER", "ADMIN").antMatchers("/index")
.hasAnyRole("USER", "ADMIN").antMatchers("/dashboard").hasAnyRole("USER", "ADMIN")
.antMatchers("/login").hasRole("ANONYMOUS").and().formLogin().loginPage("/login")
.defaultSuccessUrl("/dashboard").usernameParameter("username")
.passwordParameter("password").and().rememberMe()
.tokenValiditySeconds(Integer.parseInt(env.getProperty("session.tokenValidity")))
.key(env.getProperty("session.key")).and().logout().logoutSuccessUrl("/login").and()
.exceptionHandling().accessDeniedPage("/403").and().csrf();
}
@Bean
public Md5PasswordEncoder passwordEncoder(){
Md5PasswordEncoder encoder = new Md5PasswordEncoder();
return encoder;
}
}
And hre is my UserService:
@Service
@Transactional(readOnly = true)
public class UserService implements UserDetailsService {
private UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
org.fingerlinks.ebook.model.bean.User user = null;
if (userRepository!=null) {
user = userRepository.findByUsername(username);
}
if (user != null) {
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new User(user.getUsername(), user.getPassword(), authorities);
}
throw new UsernameNotFoundException("User '" + username + "' not found");
}
}
My problem is that user, in login page, can't login if I use passwordEncoder with an encrypted password on user table. But if I remove encoding in java code and in user table, all work well. Can anyone help me to understand where is the terrible mistake?
I'm using spring 4.1.6 and spring security 4.0.2.