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

Erro Login com Spring Security

Olá, Estou com o seguinte erro no login:

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

Ele dá esse erro a primeira vez que tento fazer o login, aí quando tento pela segunda vez ele entra. Se eu fizer logout e tentar fazer login de novo ele dá o mesmo erro, ai tenho que tentar uma segunda vez pra logar.

Alguém saberia dizer o que poderia ser?

Obrigado

@Controller
public class LoginController {

    @RequestMapping(value="/login", method=RequestMethod.GET)
    public ModelAndView loginForm() {
        return new ModelAndView("/loginForm");
    }

}
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Livros de Java, Android, iPhone, PHP, Ruby e muito mais - Casa do Código</title>
<c:url value="/resources/css" var="cssPath" />
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="${cssPath}/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="${cssPath}/bootstrap-theme.min.css">
<%-- <!-- Latest compiled and minified JavaScript -->
<script src="resources/js/bootstrap.min.js"></script>
</head> --%>
<style type="text/css">
    body {
        padding-bottom: 60px;
    }
</style>
<body>
    <div class="container">
        <h1>Login da Casa do Código</h1>
        <form:form servletRelativeAction="/login" method="POST">
            <div class="form-group">
                <label>E-mail</label>
                <input name="username" type="text" class="form-control"/>
            </div>
            <div class="form-group">
                <label>Senha</label>
                <input name="password" type="password" class="form-control" />
            </div>
            <button type="submit" class="btn btn-primary">Logar</button>
        </form:form>
    </div>
</body>
</html>

@EnableWebMvc
@ComponentScan(
        basePackageClasses= {
                HomeController.class,
                ProdutoDAO.class,
                FileSaver.class,
                CarrinhoCompras.class
            })
@EnableCaching
public class AppWebConfiguration implements WebMvcConfigurer  {

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");

        resolver.setExposedContextBeanNames("carrinhoCompras");

        return resolver;
    }

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("/WEB-INF/messages");
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setCacheSeconds(1);
        return messageSource;
    }

    @Bean //PARA Datas antes Java8
    public FormattingConversionService mvcConversionService() {
        DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
        DateFormatterRegistrar registrar = new DateFormatterRegistrar();
        registrar.setFormatter(new DateFormatter("dd/MM/yyyy"));
        registr
3 respostas

Está dando 404?

Sim Guilherme, 404 e a mensagem que passei. Se souber como resolver, eu agradeço. Obrigado

solução!

Bom dia.

Eu fiz seguindo os vídeos e ou ficou faltando as configurações certas ou eu deixei passar... De qualquer forma, baixando o projeto já pronto no capítulo adiante funcionou.

Deve ficar assim:

package br.com.casadocodigo.loja.conf;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import br.com.casadocodigo.loja.dao.UsuarioDAO;

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UsuarioDAO usuarioDAO;

    //primeiro bloqueia depois libera
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
//            .antMatchers("/resources/**").permitAll()
            .antMatchers("/produtos/form").hasRole("ADMIN")
            .antMatchers("/produtos").hasRole("ADMIN")
            .antMatchers("/produtos/").hasRole("ADMIN")
            .antMatchers("/produtos/**").permitAll()
            .antMatchers("/carrinho/**").permitAll()    
            .antMatchers("/pagamento/**").permitAll()    
            .antMatchers("/").permitAll()
            .anyRequest().authenticated()
            .and()
                .formLogin().loginPage("/login").defaultSuccessUrl("/produtos").permitAll()
            .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll() 
                .logoutSuccessUrl("/login");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(usuarioDAO)
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    // Forma recomendada de ignorar no filtro de segurança as requisições para recursos estáticos
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }
}