Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There is no PasswordEncoder mapped for the id "null" with database authentication

I successfully build in-memory authentication. But when I going to build it with database comes this error.

There is no PasswordEncoder mapped for the id "null"

This is followed tutorial - Spring Boot Tutorial for Beginners, 10 - Advanced Authentication using Spring Security | Mighty Java

There are classes

SpringSecurityConfiguration.java

@Configuration
@EnableWebSecurity
public class SpringSecurityConfiguration extends 
WebSecurityConfigurerAdapter{

@Autowired
private AuthenticationEntryPoint entryPoint;

@Autowired
private MyUserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated().and().httpBasic()
        .authenticationEntryPoint(entryPoint);
}

}

AuthenticationEntryPoint.java

@Configuration
public class AuthenticationEntryPoint extends BasicAuthenticationEntryPoint{


@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {

    response.addHeader("WWW-Authenticate", "Basic realm -" +getRealmName());
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    PrintWriter writer = response.getWriter();
    writer.println("Http Status 401 "+authException.getMessage());
}

@Override
public void afterPropertiesSet() throws Exception {
    setRealmName("MightyJava");
    super.afterPropertiesSet();
}

}

MyUserDetailsService .java

@Service
public class MyUserDetailsService implements UserDetailsService{

@Autowired
private UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);
    if(user == null){
        throw new UsernameNotFoundException("User Name "+username +"Not Found");
    }
    return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassword(),getGrantedAuthorities(user));
}

private Collection<GrantedAuthority> getGrantedAuthorities(User user){

    Collection<GrantedAuthority> grantedAuthority = new ArrayList<>();
    if(user.getRole().getName().equals("admin")){
        grantedAuthority.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    }
    grantedAuthority.add(new SimpleGrantedAuthority("ROLE_USER"));
    return grantedAuthority;
}
}

UserRepository interface

public interface UserRepository extends JpaRepository<User, Long>{

@Query("FROM User WHERE userName =:username")
User findByUsername(@Param("username") String username);

}

Role.java

@Entity
public class Role extends AbstractPersistable<Long>{

private String name;

@OneToMany(targetEntity = User.class , mappedBy = "role" , fetch = FetchType.LAZY ,cascade = CascadeType.ALL)
private Set<User> users;

//getter and setter
}

User.java

@Entity
public class User extends AbstractPersistable<Long>{

//AbstractPersistable class ignore primary key and column annotation(@Column)

private String userId;
private String userName;
private String password;

@ManyToOne
@JoinColumn(name = "role_id")
private Role role;

@OneToMany(targetEntity = Address.class, mappedBy = "user",fetch= FetchType.LAZY ,cascade =CascadeType.ALL)
private Set<Address> address; //Instead of Set(Unordered collection and not allow duplicates) we can use list(ordered and allow duplicate values) as well

//getter and setter}

If you have any idea plese inform. Thank you.

like image 460
Priyantha Avatar asked Apr 02 '18 19:04

Priyantha


1 Answers

I changed MyUserDetailsService class adding passwordEncoder method.

Added lines

BCryptPasswordEncoder encoder = passwordEncoder();

Changed Line

//changed, user.getPassword() as encoder.encode(user.getPassword())
return new org.springframework.security.core.userdetails.User(--)

MyUserDetailsService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    BCryptPasswordEncoder encoder = passwordEncoder();
    User user = userRepository.findByUsername(username);
    if(user == null){
        throw new UsernameNotFoundException("User Name "+username +"Not Found");
    }
    return new org.springframework.security.core.userdetails.User(user.getUserName(),encoder.encode(user.getPassword()),getGrantedAuthorities(user));
}

@Bean
public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
like image 150
Priyantha Avatar answered Oct 10 '22 22:10

Priyantha