Estou programando um backend para uma API de uma biblioteca com objetivos acadêmicos, porém no momento estou empacado em um erro referente a meu repositório da classe Usuário
org.springframework.security.authentication.InternalAuthenticationServiceException:
Cannot invoke
"br.ufsm.poow2.biblioteca_rest.repository.UsuarioRepo.findUsuarioByEmailUsuario(String)"
because "this.usuarioRepo" is null
A variável usuarioRepo é tida como nulo ao tentar executar o método 'findUsuarioByEmailUsuario', método esse que está sendo utilizado para devolver o objeto Usuário encontrado no Repository através do email
O problema é que a variável 'usuarioRepo' retorna tranquilamente a lista de usuários no Postman, porém na tentativa de login (Por onde o método findUsuarioByEmailUsuario é utilizado), esse erro ocorre
Postman retorna a lista de usuário existentes do BD
Postman bloqueia o usuário mesmo com o email e a senha corretas
Esse erro no Postman com o login ocorre justamente porque esse método não retorna nenhum usuário, por conta do erro de usuarioRepo nulo
Meu UsuarioService:
package br.ufsm.poow2.biblioteca_rest.service;
import br.ufsm.poow2.biblioteca_rest.model.Usuario;
import br.ufsm.poow2.biblioteca_rest.repository.UsuarioRepo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UsuarioService {
@Autowired
UsuarioRepo usuarioRepo;
public boolean criarUsuario(Usuario usuario){
String senha = usuario.getSenhaUsuario();
usuario.setSenhaUsuario(new BCryptPasswordEncoder().encode(senha));
if (usuario.getPermissaoUsuario().equals("usr") || usuario.getPermissaoUsuario().equals("adm")){
usuarioRepo.save(usuario);
return true;
}
return false;
}
public void atualizarTokenJWT(Usuario usuario, String tokenJWT){
usuario.setTokenUsuario(tokenJWT);
usuarioRepo.save(usuario);
}
public List<Usuario> listarUsuario(){
return usuarioRepo.findAll();
}
public void editarUsuario(Integer idUsuario, Usuario editarUsuario){
Optional<Usuario> usuario = usuarioRepo.findById(idUsuario);
usuario.get().setNomeUsuario(editarUsuario.getNomeUsuario());
usuario.get().setSenhaUsuario(editarUsuario.getSenhaUsuario());
usuario.get().setEmailUsuario(editarUsuario.getEmailUsuario());
usuarioRepo.save(usuario.get());
}
public Usuario getUsuarioByEmail(String emailUsuario){
System.out.println("Email user: " + emailUsuario);
return usuarioRepo.findUsuarioByEmailUsuario(emailUsuario);
}
public boolean findById(Integer idUsuario) {
return usuarioRepo.findById(idUsuario).isPresent();
}
}
Meu UsuarioRepo
package br.ufsm.poow2.biblioteca_rest.repository;
import br.ufsm.poow2.biblioteca_rest.model.Usuario;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UsuarioRepo extends JpaRepository<Usuario, Integer> {
Usuario findUsuarioByEmailUsuario(String email);
}
Minha classe usuário:
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table
@Entity(name = "Usuario")
public class Usuario {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer idUsuario;
@Column(name = "nomeUsuario")
private @NotBlank String nomeUsuario;
@Column(name = "emailUsuario", unique=true)
private @NotBlank String emailUsuario;
@Column(name = "senhaUsuario")
private @NotBlank String senhaUsuario;
@Column(name = "permissaoUsuario")
private @NotBlank String permissaoUsuario;
@Column(name = "tokenUsuario")
private String tokenUsuario;
}
Meu LoginController
@RestController
public class LoginController {
@Autowired
UsuarioService usuarioService;
@Autowired
AuthenticationManager authenticationManager;
@PostMapping("/login")
public ResponseEntity<Object> autenticacao(@RequestBody Usuario usuario){
System.out.println("Email: " + usuario.getEmailUsuario() + "\nSenha: " + usuario.getSenhaUsuario());
try{
final Authentication authentication = this.authenticationManager
.authenticate(
new UsernamePasswordAuthenticationToken(usuario.getEmailUsuario(),
usuario.getSenhaUsuario()
)
);
if (authentication.isAuthenticated()){
SecurityContextHolder.getContext().setAuthentication(authentication);
System.out.println("Gerando TOCKEN de autenticação");
String token = new JWTUtil().geraToken(usuario);
usuarioService.atualizarTokenJWT(usuario, token);
return new ResponseEntity<>(usuario, HttpStatus.OK);
}
}catch(Exception E){
E.printStackTrace();
return new ResponseEntity<>(
"Usuário ou senha incorretos",
HttpStatus.BAD_REQUEST
);
}
return null;
}
}
A tabela usuário no banco de dados
Stacktrace completa:
org.springframework.security.authentication.InternalAuthenticationServiceException: Cannot invoke "br.ufsm.poow2.biblioteca_rest.repository.UsuarioRepo.findUsuarioByEmailUsuario(String)" because "this.usuarioRepo" is null
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:108)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:133)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:182)
at br.ufsm.poow2.biblioteca_rest.controller.LoginController.autenticacao(LoginController.java:30)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
at java.base/java.lang.reflect.Method.invoke(Method.java:578)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1071)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:964)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:696)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:779)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:111)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:337)
at org.springframework.security.web.access.intercept.AuthorizationFilter.doFilterInternal(AuthorizationFilter.java:73)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:122)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:109)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346)
at br.ufsm.poow2.biblioteca_rest.security.FiltroAutenticacao.doFilterInternal(FiltroAutenticacao.java:54)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:112)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:82)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346)
at org.springframework.security.web.session.DisableEncodeUrlFilter.doFilterInternal(DisableEncodeUrlFilter.java:42)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:346)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:221)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:186)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:1589)
Caused by: java.lang.NullPointerException: Cannot invoke "br.ufsm.poow2.biblioteca_rest.repository.UsuarioRepo.findUsuarioByEmai lUsuario(String)" because "this.usuarioRepo" is null
at br.ufsm.poow2.biblioteca_rest.service.UsuarioService.getUsuarioByEmail(UsuarioService.java:47)
at br.ufsm.poow2.biblioteca_rest.security.UserDetailServiceCustomizado.loadUserByUsername(UserDetailServiceCustomizado.java:17)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:93)
... 95 more
Meu UserDetailServiceCustomizado:
@Service
public class UserDetailServiceCustomizado implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String emailUsuario) throws UsernameNotFoundException {
Usuario usuario = new UsuarioService().getUsuarioByEmail(emailUsuario);
// Usuario usuario = new UsuarioDao().getUsuario(username);
if (usuario == null){
throw new UsernameNotFoundException("Usuário ou senha inválidos");
}else{
UserDetails user = User.withUsername(usuario.getEmailUsuario())
.password(usuario.getSenhaUsuario())
.authorities(usuario.getPermissaoUsuario()).build();
return user;
}
}
}
emailUsario
, ou simplesmenteemail
? se for o segundo caso sugiro renomear o metodo em UsuarioRepo parafindUsuarioByEmail