My application with Spring Security don't go beyond login page
Asked Answered
D

1

2

I just started a project with uses Spring Security for authentication which uses Java configuration instead XML. That's my class SecurityConfig.java:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("kleber")
                .password("123")
                .roles("USER");
    }

    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers("/css/**", "/fonts/**", "/image/**", "/js/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/spring/index").permitAll()
                            .loginProcessingUrl("/spring/login").permitAll()
                .usernameParameter("login")
                .passwordParameter("senha")
                .defaultSuccessUrl("/spring/home")
                .failureUrl("/spring/erro-login")
                .and()
            .logout()
                .logoutUrl("/spring/logout")
                .logoutSuccessUrl("/spring/index").permitAll();
    }

}

With this configuration, I can reach the login page, but after I inform my credencials (username and password) the system return to this same login page, despite the username and password informed are correct.

All this URLs informed in the class SecurityConfig are mapped in this controller:

@Controller
@RequestMapping(value="spring")
public class SpringController {

    @RequestMapping(value="index")
    public ModelAndView index() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("index");
        return mav;
    }

    @RequestMapping(value="home")
    public ModelAndView home() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("home");
        return mav;
    }

    @RequestMapping(value="doLogin", method=RequestMethod.POST)
    public void doLogin(HttpServletRequest request, HttpServletResponse response) {
        //
    }

    @RequestMapping(value="logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath());
    }

}

What I am doing wrong?

-->Still related to topic above:

I need implement this 'loginProcessingUrl', which is mapped in my controller this way:

@RequestMapping(value="doLogin", method=RequestMethod.POST)
public void doLogin(HttpServletRequest request, HttpServletResponse response) {
    //
}

I already have in my application two classes which, according to the articles I read, will be necessary for this process, but I could be wrong and maybe i need another approach:

SampleAuthenticationManager

public class SampleAuthenticationManager implements AuthenticationManager {
  static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();

  static
  {
    AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
  }

  public Authentication authenticate(Authentication auth) throws AuthenticationException
  {
    if (auth.getName().equals(auth.getCredentials()))
    {
        return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(), AUTHORITIES);
    }
    throw new BadCredentialsException("Bad Credentials");
  }

}

DefaultAuthenticationProcessingFilter

    public class DefaultAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {

    private static final String INTERCEPTOR_PROCESS_URL = "/spring/doLogin";

    private static AuthenticationManager am = new SampleAuthenticationManager();

    protected DefaultAuthenticationProcessingFilter() {
        super(INTERCEPTOR_PROCESS_URL);
        // TODO Auto-generated constructor stub
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        // TODO Auto-generated method stub

        String login = request.getParameter("login");
        String senha = request.getParameter("senha");

        Authentication input = new UsernamePasswordAuthenticationToken(login, senha);
        Authentication output = null;
        try {
            output = am.authenticate(input);
            SecurityContextHolder.getContext().setAuthentication(output);
            getSuccessHandler().onAuthenticationSuccess(request, response, output);
        } catch (AuthenticationException failed) {
            getFailureHandler().onAuthenticationFailure(request, response, failed);
        }

        return output;
    }

}

In this scenario, how I should implement the method doLogin from my controller? Take in consideration that in this moment I am using inMemory authentication, for later extend my project for use a database.

Dwarfism answered 30/3, 2014 at 0:25 Comment(1)
i don't see anywhere you are registering your AuthenticationManager or AuthenticationProvider implementations. The lines using the authenticationmanagerbuilder are registering some built in managers and providers. Also the line auth.getName().equals(auth.getCredentials()) would imply that the username and password (or whatever credential) would have to be the same to authenticate with your manager.Seismoscope
D
2

Ok, I managed to solve my problem; it happens I make some mess with the Url informed in the SecurityConfig and the Url's in my views. I need remember in the future: in the class, use always //. In the view, always use .

In my case, the views was written this way:

index.jsp -> the login page

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<c:url value="/spring/login" var="loginUrl"/>
<form method="post" action="${loginUrl}">
    usu&aacute;rio: <input type="text" name="login" size=20> <br/>
    senha: <input type="password" name="senha" size=20> <br/>
    <input type="submit" value="entrar"> <br/>
</form>

</body>
</html>

home.jsp -> the "destiny" page (dashboard): only for test purposes in this state of project

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<h2>
    <c:out value="${pageContext.request.remoteUser}"/>
    <a href="<c:out value="${pageContext.request.contextPath}/spring/logout"/>">Logout</a>
</h2>

</body>
</html>

Final code for the class SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("kleber")
                .password("123")
                .roles("USER");
    }

    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers("/css/**", "/fonts/**", "/image/**", "/js/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/spring/index").permitAll()
                .loginProcessingUrl("/spring/login").permitAll()
                .usernameParameter("login")
                .passwordParameter("senha")
                .successHandler(new CustomAuthenticationSuccessHandler())
                .failureHandler(new CustomAuthenticationFailureHandler())
                .and()
            .logout()
                .logoutUrl("/spring/logout")
                .logoutSuccessUrl("/spring/index").permitAll();
    }

}
Dwarfism answered 30/3, 2014 at 20:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.