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

Erro ao iniciar a configuracao do Spring Security

Pessoal tudo bem ?

Estou com o seguinte problema, ao criar as classes SecurityConfiguration e SpringSecurityFilterConfiguration, fazendo a configuracao em ServletSpringMVC no metodo root, minha aplicacao para de funcionar


public class SpringSecurityFilterConfiguration extends AbstractSecurityWebApplicationInitializer {

}
@EnableWebMvcSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
}
public class ServletSpringMVC extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SecurityConfiguration.class, AppWebConfiguration.class, JPAConfiguration.class };
    }

Ao iniciar a aplicacao ocorre o seguinte erro:

HTTP Status 404 – Not Found
Type Status Report

Message /casadocodigo/produtos

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

POM.XML

as dependencias usado para o spring security é o mesmo fornecido em aulas pelo professor :D

    <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.0.0.M2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>4.0.0.M2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.1.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>4.0.0.M2</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone/</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

Segue o erro que é estourado no console do eclipse.

https://gist.github.com/sleepk/c38373c8b35769f2cd5e9e5e276d5d05

Segue o link do bitbucket aonde esta armazendo o projeto em questao:

https://bitbucket.org/Sleepk/spring-2

4 respostas

Oi Julio,

Este erro é uma incompatibilidade de versões entre o Spring Security e o Spring Web.

Dá uma olhada se a versão do Spring Web no seu pom.xml é no mínimo 4.2.x, se não for, tem que atualizar.

Abraço!

Joviane, tudo bem ?

Atualizei todas as dependencias do spring, mas mesmo assim o projeto nao executou =/.

    <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>



<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>


<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.14.RELEASE</version>
        </dependency>

Erro

HTTP Status 404 – Not Found
Type Status Report

Message /casadocodigo/produtos

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Apache Tomcat/8.5.24

Foi atualizado o bitbucket caso queira puxar o projeto.

Pessoal, boa noite!

Apos varias tentativas de fazer o projeto funcionar, ele pegou no tranco hahaha, mas agora estou com um outro problema, esta estourando o seguinte erro:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'springConfiguration': Unsatisfied dependency expressed through field 'usarioDAO'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'br.com.casadocodigo.loja.dao.UsuarioDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at 
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'br.com.casadocodigo.loja.dao.UsuarioDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
    at

Classe usuarioDAO

@Repository
public class UsuarioDAO implements UserDetailsService {

    @PersistenceContext
    private EntityManager manager;

    public Usuario loadUserByUsername(String email) {
        List<Usuario> usuarios = manager.createQuery("select u from usuario u where u.email = :pEmail", Usuario.class)
                .setParameter("pEmail", email).getResultList();

        if (usuarios.isEmpty()) {
            throw new UsernameNotFoundException("Usuario: " + email + " nao foi encontrado");
        }

        return usuarios.get(0);

    }
}

ServletSpringMVC

@Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { SecurityConfiguration.class, AppWebConfiguration.class, JPAConfiguration.class };
    }

SpringConfiguration

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Autowired
    private UsuarioDAO usuarioDAO;

    // ira configura as configuracoes e permissoes. 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/produtos/form").hasRole("ADMIN")
            .antMatchers("/carrinho").permitAll()
                .antMatchers(HttpMethod.POST, "/produtos").hasRole("ADMIN")
                .antMatchers(HttpMethod.POST, "/produtos")
                .hasRole("ADMIN").antMatchers("/produtos/**").permitAll()
                .antMatchers("/").permitAll().anyRequest()
                .authenticated().and().formLogin();
    }


    // metodo que cuida dos detalhes dos usuarios
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(usuarioDAO)
        .passwordEncoder(new BCryptPasswordEncoder());

    }

}
solução!

Joviane, tudo bem ?

Problema foi solucionado, a classe produtoDAO estava dentro do pacote daos, ao renomear o pacote para dao, o projeto executou normalmente :D