Home > database >  CrudRepository return null
CrudRepository return null

Time:10-29

I can't find where is a problem. I'm searching inside DB the user by Username and Password. But it return null.

This is my Repository:

@Repository
public interface UserCrudRepository extends CrudRepository<User, Integer>{

List<User> findByUsernameAndPassword(String username, String password);}

This is my Service:

@Service
public class UserService {
@Autowired
private UserCrudRepository crudRepo;


public List<User> findByUsernameAndByPassword(String username, String password){
//List<UserModel> ut=null;
//ut= crudRepo.findByUsernameAndPassword(username, password);
return crudRepo.findByUsernameAndPassword(username, password);
}

When I debug my app, I see that inside "findByUsernameAndPassword(username, password);" the informations that user wrote are present, but the method retur null.

What's wrong here?

CodePudding user response:

Since you have encrypted passwords the best way to do this is by searching for the user only by username and then use BCryptPasswordEncoder to match your plain text password with the encoded version you have in the database. You could get a BCryptPasswordEncoder in your Service as follows:

@Service
public class UserService {
  @Autowired
  private BCryptPasswordEncoder bCryptPasswordEncode;

  @Autowired
  private UserCrudRepository crudRepo;

  public List<User> findByUsernameAndByPassword(String username, String password){
    List<User> users = crudRepo.findByUsername(username);
    for (user : users) {
       if (bCryptPasswordEncoder.matches(password, user.getPassword())) {
          // passwords match
       }
    }
  }
}

You also need to have a configuration file where you ask for a BCryptPasswordEncoder to be created:

public class SecurityConfiguration {
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

And you need to adapt your repository:

@Repository
public interface UserCrudRepository extends CrudRepository<User, Integer>{
  List<User> findByUsername(String username);
}

I assume that you are using this as a form os authentication, so you might consider taking a look at UserDetailsService interface (https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/userdetails/UserDetailsService.html) if you are not using it already.

CodePudding user response:

I think you need to write a query to fetch the user detail in the UserCrudRepository.

@Query("SELECT u FROM User u WHERE lower(u.username) LIKE %?1% AND "  
      "lower(u.password) LIKE %?2%")
List<User> findByUsernameAndPassword(String username, String password);
  • Related