Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

[Bug] Cannot invoke "UserRepository.findByEmail(String)" because "this.user_repository" is null

Estou criando uma api java, e estou recebendo o seguinte erro:

java.lang.NullPointerException: Cannot invoke "school.pachecos.api.users.UserRepository.findByEmail(String)" because "this.user_repository" is null

Esse é o código

Security Filter

@Component
public class SecurityFilter extends OncePerRequestFilter {

    @Autowired
    TokenService token_service = new TokenService();
    @Autowired
    private UserRepository user_repository;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filter_chain) throws ServletException, IOException {
        String token = getToken(request);
        if(token != null){
            String token_subject = token_service.getTokenSubject(token);
            UserDetails user_entity = user_repository.findByEmail(token_subject);
            Authentication authentication = new UsernamePasswordAuthenticationToken(user_entity, null, user_entity.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filter_chain.doFilter(request, response);
    }

    private String getToken(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if(token == null){
            return null;
        }
        return token.replace("Bearer", "");
    }

}

Security Config

@Configuration
@EnableWebSecurity
public class SecurityConfigurations {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(http_request -> http_request
                .requestMatchers("/auth/login").permitAll()
                .anyRequest().authenticated()
            )
            .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .addFilterBefore(new SecurityFilter(), UsernamePasswordAuthenticationFilter.class)
            .build();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration auth_config) throws Exception {
        return auth_config.getAuthenticationManager();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

}

Token Config

@Service
public class TokenService {

    private final String secret = "b0eMdsHE5jKDW9RsjuC5VrF8BT7P2oHubObbdBvaVbfzlXgKftxQ2WrZfX4RtU04";
    private final String ISSUER = "API Pacheco's School";

    public String createToken(UserEntity user){
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            return JWT.create()
                    .withIssuer(ISSUER)
                    .withExpiresAt(getExpiresAt())
                    .withSubject(user.getUsername())
                    .sign(algorithm);
        } catch (JWTCreationException exception){
            return null;
        }
    }

    private Instant getExpiresAt(){
        return LocalDateTime.now().plusDays(1).toInstant(ZoneOffset.of("-03:00"));
    }

    public String getTokenSubject(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            return JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .build()
                    .verify(token)
                    .getSubject();
        } catch (JWTVerificationException exception){
            return null;
        }
    }
}

User Repository

public interface UserRepository extends JpaRepository<UserEntity, Long> {

    @Query(value = "SELECT u FROM UserEntity u WHERE " +
        "u.name LIKE CONCAT('%', :name, '%') " +
        "OR u.birth_date = :date " +
        "OR u.email LIKE CONCAT('%', :email, '%') " +
        "OR cellphone LIKE CONCAT('%', :cellphone, '%') "
    )
    Collection<UserEntity> searchUsers(String name, LocalDate date, String email, String cellphone);

    UserDetails findByEmail(String email);
}

Tive o mesmo erro com o Token Service no Security Filter, mas como era uma classe, pude instancia-la e cria-la. Só que no UserRepository , como se trata de uma interface, não posso fazer isso. Alguma ideia?

2 respostas
solução!

Oi!

O problema está na sua classe SecurityConfigurations, nessa linha:

.addFilterBefore(new SecurityFilter(), UsernamePasswordAuthenticationFilter.class)

Você está instanciando manualmente o SecurityFilter e com isso o spring não vai injetar as dependências dentro dele. Você precisa injetar o SecurityFilter na classe SecurityConfigurations e passá-lo como parâmetro para o método addFilterBefore.

Oii, obrigado!! deu certinho agora!