springspring-securityautologin

AutoLogin with spring security Not Working


I have implemented autoLogin functionality after successful registeration of user. But it stops on

Authentication authenticatedUser = authenticationManager.authenticate(usernamePasswordAuthenticationToken)

without giving any error. Can anybody correct where I'm getting wrong?

SecurityConfiguration.java

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomSuccessHandler customSuccessHandler;
    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

        auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(passwordEncoder())
                .usersByUsernameQuery("SELECT username, password, enabled FROM users WHERE username = ?")
                .authoritiesByUsernameQuery("SELECT username, authority FROM authorities WHERE username = ?");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {

        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Autowired
    @Bean(name = "authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /*
     * @Bean public DaoAuthenticationProvider authenticationProvider() {
     * DaoAuthenticationProvider authenticationProvider = new
     * DaoAuthenticationProvider();
     * authenticationProvider.setPasswordEncoder(passwordEncoder()); return
     * authenticationProvider; }
     */

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/home/**").access("hasRole('ROLE_USER')")
            .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
            .and()

        .formLogin()
        .loginPage("/login").failureUrl("/login?error").loginProcessingUrl("/j_spring_security_check")
        .successHandler(customSuccessHandler).usernameParameter("username").passwordParameter("password").and()
        .logout().logoutSuccessUrl("/j_spring_security_logout").and().exceptionHandling()
        .accessDeniedPage("/403").and().csrf().and().rememberMe().tokenRepository(persistentTokenRepository())
        .tokenValiditySeconds(86400);
        /*
         * .and().exceptionHandling().accessDeniedPage("/Access_Denied");
         */ }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl db = new JdbcTokenRepositoryImpl();
        db.setDataSource(dataSource);
        return db;
    }

    @Bean
    public AuthenticationTrustResolver getAuthenticationTrustResolver() {
        return new AuthenticationTrustResolverImpl();
    }

}

This is my registeration request mapping:

@RequestMapping(value = "/registerHere", method = RequestMethod.POST)
public ModelAndView registerUser(@ModelAttribute("user") Users user, BindingResult result,
        HttpServletRequest request, HttpServletResponse response) {
    System.out.println("Starting register");

    ModelAndView mv = new ModelAndView("/home");
    mv.addObject("homePagee", "true");

    String uname = user.getUsername();

    if (userDAO.getUserByName(uname) == null) {

        userDAO.saveOrUpdate(user);
        /*
         * userDAO.autologin(user.getUsername(), user.getPassword());
         */
        authenticateUserAndSetSession(user, request);


    }

    System.out.println("ending register");

    log.debug("Ending of the method registerUser");
    return mv;
}
private void authenticateUserAndSetSession(Users user, HttpServletRequest request){

    String username = user.getUsername();
    String password = user.getPassword();
    System.out.println("username:  " + username + " password: " + password);                        

    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
    request.getSession();

    System.out.println("Line Authentication 1");

    usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetails(request));

    System.out.println("Line Authentication 2");

    Authentication authenticatedUser = authenticationManager.authenticate(usernamePasswordAuthenticationToken);// authenticates the token

    System.out.println("Line Authentication 3");


    if (usernamePasswordAuthenticationToken.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
        System.out.println("Line Authentication 4");

    }

 request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());// creates context for that session.

    System.out.println("Line Authentication 5");

    session.setAttribute("username", user.getUsername());

    System.out.println("Line Authentication 6");

    session.setAttribute("authorities", usernamePasswordAuthenticationToken.getAuthorities());

    System.out.println("username:  " + user.getUsername() + "password: " + user.getPassword()+"authorities: "+ usernamePasswordAuthenticationToken.getAuthorities());

    user = userDAO.validate(user.getUsername(), user.getPassword());
    log.debug("You are successfully register");

}

When I register Console:

Hibernate: 
insert 
into
    Cart
    (addedDate, grandTotal, usersID, cartId) 
values
    (?, ?, ?, ?)
Hibernate: 
    update
        USERS 
    set
        billingAddressId=?,
        cartId=?,
        email=?,
        enabled=?,
        mobile=?,
        name=?,
        password=?,
        role=?,
        shippingAddressId=?,
        STATE=?,
        username=? 
    where
        usersID=?
    username:  do password: $2a$10$YX.AKZYoI0g7xAN8mzlHOurK8Hys4aX2Iw75OE.6qgpZ6PeV4qHoy
    Line Authentication 1
    Line Authentication 2

It stops after Line Authentication 2 any idea what i m missing?


Solution

  • I have solved and answer to above question is In Controller:

    @RequestMapping(value = "/registerHere", method = RequestMethod.POST)
        public ModelAndView registerUser(@ModelAttribute("user") Users user, BindingResult result,
                HttpServletRequest request, HttpServletResponse response) {
            System.out.println("register 3");
    
            ModelAndView mv = new ModelAndView("/home");
            mv.addObject("homePagee", "true");
    
            String uname = user.getUsername();
    
            if (userDAO.getUserByName(uname) == null) {
    
                String passwordFromForm = user.getPassword();
                userDAO.saveOrUpdate(user);
    
                try {
                    authenticateUserAndSetSession(user, passwordFromForm, request);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
    
            }
    
            System.out.println("register 4");
    
            log.debug("Ending of the method registerUser");
            return mv;
        }
    

    Further above method in controller is defined as:

     private void authenticateUserAndSetSession(Users user, String passwordFromForm, HttpServletRequest request){
    
            String username = user.getUsername();
            System.out.println("username:  " + username + " password: " + passwordFromForm);                        
    
            UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());
    
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, passwordFromForm, userDetails.getAuthorities());
            request.getSession();
    
            System.out.println("Line Authentication 1");
    
            usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetails(request));
    
            System.out.println("Line Authentication 2");
    
            Authentication authenticatedUser = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
    
            System.out.println("Line Authentication 3");
    
    
            if (usernamePasswordAuthenticationToken.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
                System.out.println("Line Authentication 4");
    
            }
    
         request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());// creates context for that session.
    
            System.out.println("Line Authentication 5");
    
            session.setAttribute("username", user.getUsername());
    
            System.out.println("Line Authentication 6");
    
            session.setAttribute("authorities", usernamePasswordAuthenticationToken.getAuthorities());
    
            System.out.println("username:  " + user.getUsername() + "password: " + user.getPassword()+"authorities: "+ usernamePasswordAuthenticationToken.getAuthorities());
    
            user = userDAO.validate(user.getUsername(), user.getPassword());
            log.debug("You are successfully register");
    
        }
    

    Other answers didnt suggest to put it in try/catch so one does not realize why logic is not working as code runs...and nothing is there neither error or exception on console. So if you wont put it in try catch you wont get exception of bad credentials.