0

I was building a Spring authentication application and cannot solve this problem.

I created 2 services Register and Authenticate.

public AuthenticationResponse register(RegisterRequest request) {
        var user = User
                .builder()
                .firstname(request.getFirstname())
                .lastname(request.getLastname())
                .email(request.getEmail())
                .password(passwordEncoder.encode(request.getPassword()))
                .role(Role.USER)
                .build();
        userRepository.save(user);
        var JwtToken = jwtService.generateToken(user);
        return AuthenticationResponse
                .builder()
                .token(JwtToken)
                .build();
    }

    public AuthenticationResponse authenticate(AuthenticationRequest request) {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
                    request.getEmail(),
                    request.getPassword()
            ));

            var user = userRepository.findByEmail(request.getEmail())
                    .orElseThrow(() -> new Exceptions.UsernameNotFoundException("User not found"));

            var jwtToken = jwtService.generateToken(user);

            return AuthenticationResponse.builder()
                    .token(jwtToken)
                    .build();
        } catch (AuthenticationException e) {
            System.out.println(e);
            throw new Exceptions.InvalidCredentialsException("Invalid email or password");
        }
    }

In this Register works perfectly but when I send post request to authenticate it throws an error:

org.springframework.security.authentication.InternalAuthenticationServiceException: Cannot invoke "breakthroughpvt.ltd.backend.Repository.UserRepository.findByEmail(String)" because "this.userRepository" is null >

UserRepository.java

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {

    Optional<User> findByEmail(String email);

I tried adding and removing @Autowired and nothing changed.

James Z
  • 12,209
  • 10
  • 24
  • 44

0 Answers0