1
good afternoon!
I am in a system with Primefaces, Hibernate, CDI and am implementing security with Spring-Security and control transactions with Hibernatefilter, declared on web.xml. I did all the tests with authentication in memory and it was right td, but when I try to create the Userdetails the application runs, it displays the login screen but when I click on the login button an error occurs. Follow below the error and my classes.
18-Jan-2017 17:35:05.197 SEVERE [http-nio-8084-exec-18] com.sistemaac.springsecurity.SACUserDetailsService.loadUserByUsername Problemas com a tentativa de conexão!
org.hibernate.HibernateException: createCriteria is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
at com.sun.proxy.$Proxy145.createCriteria(Unknown Source)
at com.sistemaac.config.dao.GenericDaoImpl.iniciarCriteria(GenericDaoImpl.java:58)
at com.sistemaac.ti.seguranca.dao.UsuarioDao.findByUserName(UsuarioDao.java:113)
at com.sistemaac.ti.seguranca.business.UsuarioBusiness.findByUserName(UsuarioBusiness.java:73)
at com.sistemaac.ti.seguranca.business.UsuarioBusiness$Proxy$_$$_WeldClientProxy.findByUserName(Unknown Source)
at com.sistemaac.springsecurity.SACUserDetailsService.buscarUsuario(SACUserDetailsService.java:64)
at com.sistemaac.springsecurity.SACUserDetailsService.loadUserByUsername(SACUserDetailsService.java:49)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:144)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:214)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Sacuserdetailsservice class:
public class SACUserDetailsService implements UserDetailsService {
private static final Logger logger = Logger.getLogger(SACUserDetailsService.class.getSimpleName());
private final UsuarioBusiness usuarioBusiness = CDIServiceLocator.getBean(UsuarioBusiness.class);
private final GrupoPermissaoBusiness grupoPermissaoBusiness = CDIServiceLocator.getBean(GrupoPermissaoBusiness.class);
public SACUserDetailsService() {
}
@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
try {
SACUserDetails userDetails = buscarUsuario(login);
Collection<GrantedAuthority> permissoesPorUsuario = buscarPermissoes(login);
userDetails.getAuthorities().addAll(permissoesPorUsuario);
return userDetails;
} catch (Exception e) {
logger.log(Level.SEVERE, "Problemas com a tentativa de conexão!", e);
throw new UsernameNotFoundException("Problemas com a tentativa de conexão!", e);
}
}
public SACUserDetails buscarUsuario(String login) throws SQLException {
Usuario usuario = usuarioBusiness.findByUserName(login);
String nome;
String password;
boolean ativo;
if(usuario !=null){
throw new UsernameNotFoundException("Usuário " + login + " não encontrado!");
}else{
nome = usuario.getLogin();
password = usuario.getSenha();
ativo = usuario.getAtivo();
}
return new SACUserDetails(nome, login, password, ativo);
}
public Collection<GrantedAuthority> buscarPermissoes(String login) throws SQLException {
List<GrantedAuthority> permissoes = new ArrayList<>();
Usuario usuario = usuarioBusiness.findByUserName(login);
for(Iterator<GrupoPermissao> iter = usuario.getGrupoPermissaoUsuarios().iterator();
iter.hasNext();) {
permissoes.add(new SimpleGrantedAuthority(grupoPermissaoBusiness.preparaPermissao(iter.next()).getGrupoPermissao()));
}
return permissoes;
}
}
User class:
@RequestScoped
@Getter
@Setter
public class UsuarioBusiness implements Serializable{
private static final long serialVersionUID = 1L;
private UsuarioLazyDataModel usuarios;
@Inject
private GrupoPermissaoBusiness grupoPermissaoBusiness;
private UsuarioDao usuarioDao = CDIServiceLocator.getBean(UsuarioDao.class);
public Usuario findByUserName(String login){
return usuarioDao.findByUserName(login);
}
}
User Class:
@Dependent
public class UsuarioDao extends FiltroGenericDao<Usuario> implements Serializable{
public UsuarioDao() {
super(Usuario.class);
}
//Filtro usado no Lazy loading
public List<Usuario> filtrados(UsuarioFiltro filtro){
Criteria criteria = criarCriteriaFiltro(filtro);
criteria.setFirstResult(filtro.getPrimeiroRegistro());
criteria.setMaxResults(filtro.getQuantidadeRegistro());
if(filtro.isAscendente() && filtro.getPropriedadeOrdenacao() != null){
criteria.addOrder(Order.asc(filtro.getPropriedadeOrdenacao()));
}else if(filtro.getPropriedadeOrdenacao() != null){
criteria.addOrder(Order.desc(filtro.getPropriedadeOrdenacao()));
}
return criteria.list();
}
//Retorna a quantidade de Acessos filtrados
public int quantidadeFiltrado(UsuarioFiltro filtro){
Criteria criteria = criarCriteriaFiltro(filtro);
//Faz o count dos registros
criteria.setProjection(Projections.rowCount());
//Como o resultado do rowcount é um único registro retorna uniqueResult
return ((Number) criteria.uniqueResult()).intValue();
}
@Override
public Criteria criarCriteriaFiltro(IFiltro filtro) {
Criteria criteria = iniciarCriteria(null);
UsuarioFiltro auxFiltro = (UsuarioFiltro) filtro;
if(auxFiltro.getUsuario()!=null && !auxFiltro.getUsuario().trim().isEmpty()){
criteria.add(Restrictions.ilike("login", auxFiltro.getUsuario().trim(), MatchMode.ANYWHERE));
}
return criteria;
}
public Boolean loginExiste(Usuario usuario) {
Criteria criteria = iniciarCriteria(null);
Criteria results = criteria.add(Restrictions.like("login", usuario.getLogin().trim(), MatchMode.EXACT));
if(results.uniqueResult() != null){
return true;
}else{
return false;
}
}
public Boolean emailExiste(Usuario usuario) {
Criteria criteria = iniciarCriteria(null);
Criteria results = criteria.add(Restrictions.like("email", usuario.getEmail().trim(), MatchMode.EXACT));
if(results.uniqueResult() != null){
return true;
}else{
return false;
}
}
public Boolean emailExisteByLogin(Usuario usuario) {
Criteria criteria = iniciarCriteria(null);
Criteria results = criteria.add(Restrictions.like("email", usuario.getEmail().trim(), MatchMode.EXACT));
criteria.add(Restrictions.like("login", usuario.getLogin().trim(), MatchMode.EXACT));
if(results.uniqueResult() != null){
return true;
}else{
return false;
}
}
public Boolean cpfExiste(Usuario usuario) {
Criteria criteria = iniciarCriteria(null);
Criteria results = criteria.add(Restrictions.like("cpf", usuario.getCpf(), MatchMode.EXACT));
if(results.uniqueResult() != null){
return true;
}else{
return false;
}
}
public Usuario findByUserName(String login) {
Criteria criteria = iniciarCriteria(null);
Criteria results = criteria.add(Restrictions.like("login", login.trim(), MatchMode.EXACT));
return (Usuario) results.uniqueResult();
}
public Usuario findByCpf (String cpf) {
Criteria criteria = iniciarCriteria(null);
Criteria results = criteria.add(Restrictions.like("cpf", cpf.trim(), MatchMode.EXACT));
return (Usuario) results.uniqueResult();
}
}
The second line points to the error: createCriteria is not Valid without active transaction. You need to open a transaction to use the criteria.
– adelmo00
This is @adelmo00, dear, only my transactions are in Hibernatefilter, every operation calls the filter and executes the transactions. It’s like spring security won’t accept the filter.
– Elton Mário da Silva
Take out the annotation:
@Dependent
, and try again. If an error requires a transaction, then put@Transactional
– danilo
can also write down your dao with:
@Repository
, so it will always open a transaction– danilo
or at the mercy, you can open the transaction in hand.. I don’t see how something very elegant: https://stackoverflow.com/a/20296980/935330
– danilo