Wildfly 10 + Spring Security + JSF + CDI Does Not Inject Dependency

Asked

Viewed 823 times

1

I’m trying to implement CDI in a WEB project I have where I use Wildfly10 with Spring Security (custom login) and JSF and I’m not being able to inject dependencies.

In the Example below the User when using the

Caused by: java.lang.Nullpointerexception at br.com.transportesalvorada.security.configall.ServicoDetailingUsuario.loadUserByUsername(Servicodetalhousuario.java:39)

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.enterprise.context.Dependent;
import javax.inject.Inject;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import br.com.transportesalvorada.security.bean.Usuario;
import br.com.transportesalvorada.security.dao.UsuarioDao;


@Service("servicoDetalhamentoUsuario")
public class ServicoDetalhamentoUsuario implements UserDetailsService, Serializable {

    private static final long serialVersionUID = 1L;

    @Inject 
    private UsuarioDao usuarioDao;


    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

        System.out.println("\n---[ServicoDetalhamentoUsuario]--------------------------");
        System.out.println("\n email :"+ email);

        //usuarioDao = new UsuarioDao();
        Usuario usuario = usuarioDao.consulta(email);

        if(usuario != null && usuario.getEmail() != null){
            System.out.println("\n usuario :"+usuario.getEmail());
            System.out.println("\n grupos  :"+usuario.getGrupos().size());
            return new UsuarioSistema(usuario, getGrupo(usuario));
        }
        return  null;



    }

    private Collection<? extends GrantedAuthority> getGrupo(Usuario usuario) {
        List<SimpleGrantedAuthority> grupos = new ArrayList<SimpleGrantedAuthority>();
        usuario.getGrupos().forEach(g->{
            grupos.add(new SimpleGrantedAuthority(g.getNome().toUpperCase()));
        });
        return grupos;
    }

}


import java.io.Serializable;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import br.com.transportesalvorada.modeldao.dao.JpaUtil;
import br.com.transportesalvorada.security.bean.Usuario;


public class UsuarioDao implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public Usuario consulta(String email) {

        System.out.println("\n -------- Entrou no Usuario.consulta - antes do EM");

        EntityManager entityManager = new JpaUtil().geraEM();
        Usuario usuario = new Usuario();
        try{
            TypedQuery<Usuario> query = entityManager.createQuery("select u from Usuario u where u.email = :pEmail",Usuario.class);
            query.setParameter("pEmail", email);
            usuario = query.getSingleResult();
            usuario.getGrupos().size();
            return usuario;

        } catch (Exception e) {
            System.out.printf("\n Erro %s \n" , e);
        }   
        return usuario;
    }


}

My Project Structure

inserir a descrição da imagem aqui

My Pom.xml

     <dependencies>
        <!--  Testes JUnit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- CDI teste --> 
        <dependency>
            <groupId>org.jglue.cdi-unit</groupId>
            <artifactId>cdi-unit</artifactId>
            <version>3.1.2</version>
            <exclusions>
                <exclusion>
                    <artifactId>dom4j</artifactId>
                    <groupId>dom4j</groupId>
                </exclusion>
            </exclusions>
            <scope>test</scope>
        </dependency>

        <!--  Configuracao de Persistencia 
        <dependency>
            <groupId>${project.groupId}</groupId> 
            <artifactId>perolawebmodelsecurit</artifactId> 
            <version>1.0.0</version> 
        </dependency> 
        <dependency>
            <groupId>${project.groupId}</groupId> 
            <artifactId>perolawebmodeldao</artifactId> 
            <version>1.0.0</version> 
        </dependency>
        -->

        <!--  Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.0.4.RELEASE</version>
        </dependency>

        <dependency>  
            <groupId>org.primefaces</groupId>  
            <artifactId>primefaces</artifactId>  
            <version>6.0</version>  
        </dependency>
        <dependency>  
            <groupId>org.primefaces.themes</groupId>  
            <artifactId>bootstrap</artifactId>  
            <version>1.0.10</version>  
        </dependency>

        <!--  Quando for WildFly -->
        <dependency>
            <groupId>org.wildfly</groupId>
            <artifactId>wildfly-jsf</artifactId>
            <version>10.0.0.Final</version>
        </dependency>
        <!--  CDI -->
        <dependency>
           <groupId>javax.enterprise</groupId>
           <artifactId>cdi-api</artifactId>
           <version>1.2</version>
        </dependency>

        <!--  DB-Postgresql -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.4-1200-jdbc41</version>
        </dependency>
        <!--  JPA-Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.0.Final</version>
            <exclusions>
                <exclusion>
                    <artifactId>dom4j</artifactId>
                    <groupId>dom4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--  Hibernate Validator -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.4.Final</version>
            <scope>compile</scope>
        </dependency>
  </dependencies>
  • The error is in this line: User user = user) ?

  • Right. Right on this line. But actually this is just an example. It doesn’t work anywhere.

  • In the META-INF folder creates a file called Beans.xml, it can be empty.

  • It didn’t work. Obs. sorry, when I said it doesn’t work anywhere I was referring to myself within the flow of spring security. if use out of flow spring security works.

1 answer

2


You are using Spring Security and CDI, both have a different dependency injection context so CDI-managed DAO will not be available for Spring Security context.
In a project to get around this problem I had to use the following class to return the Beans that are in the CDI injection context for Spring Security to use correctly.

public class CDIServiceLocator {

    private static BeanManager getBeanManager() {
        try {
            InitialContext initialContext = new InitialContext();
            return (BeanManager) initialContext.lookup("java:comp/env/BeanManager");
        } catch (NamingException ex) {
            throw new RuntimeException("Bean não encontrado no JNDI");
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> clazz) {
        BeanManager bm = getBeanManager();
        Set<Bean<?>> beans = (Set<Bean<?>>) bm.getBeans(clazz);

        if (beans == null || beans.isEmpty()) {
            return null;
        }

        Bean<T> bean = (Bean<T>) beans.iterator().next();

        CreationalContext<T> ctx = bm.createCreationalContext(bean);
        T o = (T) bm.getReference(bean, clazz, ctx);
        return o;
    }

}

Within the method that will use the DAO place the following call:

MeuDAO meuDAO = CDIServiceLocator.getBean(MeuDAO.class);

Udate

Where is java:comp/env/BeanManager replace with java:comp/BeanManager

I did a test using Wildfly 10 and it worked correctly

  • That would be @Inject private Usersthe userDao = Cdiservicelocator.getBean(Usersdao.class);

  • This giving Caused by: org.springframework.Beans.Beaninstantiationexception: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw Exception; nested Exception is java.lang.Runtimeexception: Bean not found in JNDI at org.springframework.Beans.factory.support.SimpleInstantiationStrategy.instantiate(Simpleinstantiationstrategy.java:189) at org.springframework.Beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(Constructorresolver.java:588)

  • No, you will instantiate dao within the loadUserByUsername method

  • The amendment worked?

  • I did so within the method-> user

  • Create a context.xml file within the /webapp/META-INF folder with this content: http://pastebin.com/tZsZy1Ds

  • @Marcelo updated the answer, see if it works.

  • Sorry for the delay in returning. It worked perfectly. Thanks. What should I read to better understand the situation?

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.