Search code examples
javaspringspring-securitybcrypt

Spring Security (3.2) BCrypt isn't hashing the password from login


I'm trying to habilitate hashing in a Spring Web App login with a database in MySQL but when I introduce the correct password, the login always send me to the login again with ?error=true.

I identify that if I put exactly the password that I had in the table 'users' (that is, the hashed password) I can access correctly to the home page. All the configurations are made in XML files due to specifications of the projects. I'm new to Spring and I couldn't identify where can be the error in the context files. I use two authentication provider but I only need the BCrypt enconder in one.

I used the BCryptPasswordEncoder class for encripting a test password and saved that result in my database. The table has a colum password of type varchar(60).I didn't get any errors on the console but I can't access to the home page. The login works fine if I don't encode the passwords. Object user from UserDetails obtain the information of the user correctly.

The project is under:

  • Spring Framework 3.2.0.RELEASE
  • Spring Security 3.2.0.RELEASE

securityContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
       http://www.springframework.org/schema/security 
       http://www.springframework.org/schema/security/spring-security-3.2.xsd">

<!--    Rutas que se ignoraran  -->
<security:http pattern="/css/**" security="none"/>
<security:http pattern="/assets/**" security="none"/>
<security:http pattern="/img/**" security="none"/>
<security:http pattern="/js/**" security="none"/>
<security:http pattern="/login*" security="none"/>
<security:http pattern="/recovery/*" security="none"/>
<security:http pattern="/recovery/initRecovery/*" security="none"/>

<security:http pattern="/lock*" use-expressions="true" auto-config="true">
     <security:intercept-url pattern="/lock*" access="permitAll" />
</security:http>


<security:http  
    auto-config="true" use-expressions="true"  
    authentication-manager-ref="authenticationManager" 
    access-denied-page="/denegado" >
    <security:intercept-url pattern="/**" access="isAuthenticated()" />
    <security:form-login login-page="/login" default-target-url="/init" authentication-failure-url="/loginfailed" />
    <security:logout invalidate-session="true" logout-success-url="/" />
</security:http>

<bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
    <constructor-arg name="strength" value="10" />
</bean>

<bean id="authenticationProviderCrece" 
      class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
    <property name="userDetailsService" ref="userDetailsServicecrece"/>
</bean>


<bean id="authenticationProviderSac" 
      class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
    <property name="userDetailsService" ref="userDetailsServicesac"/>
</bean>


<bean id="authenticationManager"
    class="org.springframework.security.authentication.ProviderManager">
  <property name="providers">
    <list>
      <ref local="authenticationProviderCrece"/>
      <ref local="authenticationProviderSac"/>
    </list>
  </property>
</bean>

<security:authentication-manager>
    <security:authentication-provider user-service-ref="userDetailsServicecrece"/>
    <security:authentication-provider user-service-ref="userDetailsServicesac">
        <security:password-encoder ref="encoder"/>
    </security:authentication-provider>
</security:authentication-manager>

UsuariosDetailsServiceImpl.java

package com.segurosargos.sac.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User; 
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 com.segurosargos.sac.modelo.entidad.Usuario;
import com.segurosargos.sac.service.UsuarioService;

@Service("userDetailsServicesac")
public class UsuariosDetailsServiceImpl implements UserDetailsService {

@Resource
private UsuarioService usuarioService;

   @Override
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       System.out.println("Buscando usuario en BD SAC...");

       Usuario usuario = usuarioService.findByUsername(username);

       if (usuario != null) {

           boolean enabled = usuario.isEnabled();
           boolean accountNonExpired = usuario.isAccountNonExpired();
           boolean credentialsNonExpired = usuario.isCredentialsNonExpired();
           boolean accountNonLocked = usuario.isAccountNonLocked();

           Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
           authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

           User user = new User(usuario.getUsername(), usuario.getPassword(),
                enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);

           return user;
       }

       return null;

    }
}

Solution

  • Thank you all for your replies. I only had to modify the securityContext.xml changing the injection of PasswordEnconder directly in the DaoAuthenticationProvider. passwordEncoder is the id of the bean where the class BCryptPasswordEncoder is added.

        <bean id="authenticationProviderSac" 
          class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <property name="userDetailsService" ref="userDetailsServicesac"/>
        <property name="passwordEncoder" ref="passwordEncoder" />
    </bean>
    
    
    <bean id="authenticationManager"
        class="org.springframework.security.authentication.ProviderManager">
      <property name="providers">
        <list>
          <ref local="authenticationProviderCrece"/>
          <ref local="authenticationProviderSac"/>
        </list>
      </property>
    </bean>
    
    <security:authentication-manager>
        <security:authentication-provider user-service-ref="userDetailsServicecrece"/>
        <security:authentication-provider user-service-ref="userDetailsServicesac" />
    </security:authentication-manager>