Encoding Passwords with Acegi

Recently I was asked how to validate encoded passwords using the acegi security framework.  I did not know off the top of my head and so I did a little research on the subject.  What I found out was that encoding passwords using acegi was incredibly straight forward and easy.

Acegi allows for configuring an object of type PasswordEncoder on its DaoAuthenticationProvider.  By default DaoAuthenticationProvider is configured with a PlaintextPasswordEncoder which does not perform any kind of password encoding, but you can easily substitute one of its out of box PasswordEncoder implementations.  These include an Md5PasswordEncoder and ShaPasswordEncoder.  Alternatively you can easily roll out your own PasswordEncoder by implementing the encodePassword and isPasswordValid methods. 

To demonstrate, I made some small modifications to the acegi-security-sample-tutorial.war which comes with the acegi download.  The checked in source is available within the subversion project under the samples/tutorial directory.  First I added the Md5PasswordEncoder to the spring application context and configured this encoder on the DaoAuthenticationProvider.


				<bean id="passwordEncoder" class="org.acegisecurity.providers.encoding.Md5PasswordEncoder"/>

    <bean id="daoAuthenticationProvider" class="org.acegisecurity.providers.dao.DaoAuthenticationProvider">
        <property name="userDetailsService" ref="userDetailsService"/>
        <property name="userCache">
            <bean class="org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache">
                <property name="cache">
                    <bean class="org.springframework.cache.ehcache.EhCacheFactoryBean">
                        <property name="cacheManager">
                            <bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>
                        </property>
                        <property name="cacheName" value="userCache"/>
                    </bean>
                </property>
            </bean>
        </property>
        <property name="passwordEncoder" ref="passwordEncoder"/>
</bean>

In order to simulate encoded passwords within our database, I created a simple wrapper class PasswordEncodingUserDetailsService which encodes passwords returned from the InMemoryDaoImpl used within the acegi example.  The PasswordEncodingUserDetailsService encodes passwords returned from a configured UserDetailsService leveraging a PasswordEncoder.


public class PasswordEncodingUserDetailsService implements UserDetailsService {
   
    private UserDetailsService userDetailsService;
   
    private PasswordEncoder passwordEncoder;

    private SaltSource saltSource;

    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException, DataAccessException {
        UserDetails user = userDetailsService.loadUserByUsername(username);
        User encodedUser = new User(user.getUsername(), encodePassword(user), user.isEnabled(),
                user.isAccountNonExpired(),
                user.isCredentialsNonExpired(), user.isAccountNonLocked(),
                user.getAuthorities());
        return encodedUser;
   
    }

    private String encodePassword(final UserDetails userDetails) {
        Object salt = null;

        if (this.saltSource != null) {
            salt = this.saltSource.getSalt(userDetails);
        }
        return passwordEncoder.encodePassword(userDetails.getPassword(), salt);
    }

    public final void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    public final void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    public final void setSaltSource(SaltSource saltSource) {
        this.saltSource = saltSource;
    }

}

Next I wrapped the existing InMemoryDaoImpl from the acegi example, using our PasswordEncodingUserDetailsService.


        <!-- Wrap the InMemoryDao to simulate encoded passwords in our database -->
	<bean id="userDetailsService"
	    class="org.kbaum.acegisecurity.userdetails.PasswordEncodingUserDetailsService">
	    <property name="userDetailsService">
	        <!-- UserDetailsService is the most commonly frequently Acegi Security interface implemented by end users -->
	        <bean
	            class="org.acegisecurity.userdetails.memory.InMemoryDaoImpl">
	            <property name="userProperties">
	                <bean
	                    class="org.springframework.beans.factory.config.PropertiesFactoryBean">
	                    <property name="location"
	                        value="/WEB-INF/users.properties" />
	                </bean>
	            </property>
	        </bean>
	    </property>
            <property name="passwordEncoder" ref="passwordEncoder"/></bean>

Notice I referenced the same passwordEncoder I configured on the DaoAuthenticationProvider ensuring we have matching password encoding algorithms.

As a result of the above, we are reading encoded passwords from our mock database and authenticating using the Md5PasswordEncoder.