del.icio.us Digg DZone Reddit StumbleUpon
Hashing and Salting Passwords with Spring Security 2 - Willie Wheeler
« Previous | 1 | 2 | 3 | 4 | 5 | 6 | Next »

Configuring your app to secure passwords during registration

Saving secured passwords is somewhat more involved than authenticating against them. Part of the reason is that we'd like to use the same PasswordEncoder instance during registration that we used during login, partly just because it's "cleaner", and relatedly, because it allows us to avoid having to coordinate two separate PasswordEncoder instances should we decide to switch from SHA-1 to MD5, or add salt, or whatever. Basically it boils down to our being good adherents to the DRY principle.

Unfortunately, the namespace configuration for authentication-provider doesn't accept an externally-defined PasswordEncoder bean; you have to use the password-encoder namespace element inside of authentication-provider. So instead of using the namespace configuration, we're going to drop back to good, old-fashioned bean configuration.

Listing 1. Configuring a PasswordEncoder and DaoAuthenticationProvider
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-2.0.4.xsd">

    <-- 1 -->
    <beans:bean id="accountDao" class="example.HbnAccountDao" />
    
    <-- 2 -- >
    <beans:bean id="userDetailsService"
        class="example.UserDetailsServiceImpl"
        p:userDao="accountDao" />

    <-- 3 -- >
    <beans:bean id="passwordEncoder"
        class="org.springframework.security.providers.encoding.ShaPasswordEncoder" />

    <-- 4 -- >
    <beans:bean
        class="org.springframework.security.providers.dao.DaoAuthenticationProvider"
        p:userDetailsService-ref="userDetailsService"
        p:passwordEncoder-ref="passwordEncoder">
        <custom-authentication-provider />
    </beans:bean>
</beans:beans>
Authentication
Figure 1. Authentication in Spring Security 2

In the code above, we begin by creating a data access object for user accounts 1. Next we create an implementation of Spring's UserDetailsService interface, which we've called UserDetailsServiceImpl 2. UserDetailsService is essentially a service provider interface for the DaoAuthenticationProvider; it allows the latter to obtain UserDetails instances for authentication purposes. Third we create the PasswordEncoder itself 3; in this case we're using ShaPasswordEncoder, which hashes passwords using SHA (the default strength is SHA-1). Finally, we're creating a DaoAuthenticationProvider 4 and injecting it with the userDetailsService and passwordEncoder we created previously. We also include a custom-authentication-provider element to register our authentication provider with an AuthenticationManager hiding in the background.

For the curious, the AuthenticationManager in question is ProviderManager, a provider-based implementation of the AuthenticationManager interface, and it is automatically created by the http element unless you've already defined one explicitly. See figure 1 for a class diagram.

That takes care of configuration. Let's see what we need to do in order to save registrations with a hashed password.

Update AccountServiceImpl to hash the password

There are two updates you'll need to make to your AccountServiceImpl bean. The first one is that you'll need to provide a setter for a PasswordEncoder. And once you create that setter, go back to your application context configuration and make sure you're actually injecting a PasswordEncoder into the AccountServiceImpl bean.

The second update is to modify your registerAccount() method in AccountServiceImpl so that it hashes passwords:

Listing 2. Update your account service to hash passwords
public void registerAccount(Account account) {
    accountDao.save(account); // 1
    String encPassword =
        passwordEncoder.encodePassword(account.getPassword(), null); // 2
    account.setPassword(encPassword); // 3
    accountDao.save(account); // 4
}

First we save the account with the plaintext password 1. There's a reason for saving the account before actually hashing the password, but we'll have to wait until later in the recipe for the reason why. Then we hash the password 2, update it on the account 3, and save the account with the new password 4. The account now has a hashed password in the database.

Good job! You're now saving secured passwords into your database, and you're able to authenticate against them.

But I'm afraid that it's time for some bad news.

Meet the dictionary attack

Our new password storage scheme is off to a good start. It certainly prevents casual observers from accidentally seeing user passwords. But it does little to thwart the efforts of a semi-determined attacker. Let's talk about the dictionary attack.

To understand how it works, recall that hashing different strings generally results in different hashes. We can use that fact to create a big lookup table for a dictionary of potential passwords. The lookup table takes a hash and then returns the string that generated it.

As luck would have it, we don't even have to create our own lookup table. Helpful folks on the Internet have already done it for us. For instance, go to

http://gdataonline.com/seekhash.php

and enter the MD5 hash we presented earlier; namely,

3af00c6cad11f7ab5db4467b66ce503e

Voilà! You've unhashed a hash. This is called a dictionary attack.

If an attacker were to acquire a list of hashed passwords, he could make quick work of it using a dictionary of the sort just described. In some contexts that might be very bad.

Social bookmarks: del.icio.us Digg DZone Reddit StumbleUpon
« Previous | 1 | 2 | 3 | 4 | 5 | 6 | Next »

Comments (14)

Very nice article Willie... thanks
By Hema on Oct 12, 2008 at 8:44 PM PDT
Good work Dudes
By Mustafa Sait Özen on Oct 12, 2008 at 11:57 PM PDT

Nice article. Fills in a few gaps in the Spring Security documentation!

By Ross Duncan on Feb 25, 2009 at 9:35 AM PST

Hello Willie,

Do I need a custom UserDetailsServiceImpl for this?

Because I tried to do this with JdbcDaoImpl, like this:

<-- 2 -- >

class="org.springframework.security.userdetails.jdbc.JdbcDaoImpl"

p:userDao="accountDao" />

but I received a NotWritablePropertyException:

SEVERE: Servlet /FlexServer threw load() exception org.springframework.beans.NotWritablePropertyException: Invalid property 'userDao' of bean class [org.springframework.security.userdetails.jdbc.JdbcDaoImpl]: Bean property 'userDao' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter? at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:787) at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:643)

Thanks in advance, and for this very interesting article (as usual),

Greets, Jochen

By Jochen Szostek on Jun 13, 2009 at 2:00 PM PDT

Correct me if i am wrong but the line number 5 in listing 4:

Object salt = saltSource.getSalt(userDetails); 

is bound to return in the variable salt the Long representing the id of the object account. So why not use the id directly. That way we would simplify the code to something like this:

public void registerAccount(Account account) {  
accountDao.save(account);  
account.setPassword(passwordEncoder.encodePassword(password,  account.getId())); 
accountDao.save(account);  
} 

Am I oversimplifying. Please correct me if I am wrong since I will be using this stuff in a project. Thanks for the nice article.

Stole

By stole on Aug 20, 2009 at 1:52 PM PDT

I was a little hasty while submitting the post previously. The code should have read:

public void registerAccount(Account account) {  
 accountDao.save(account);  
 account.setPassword(
    passwordEncoder.encodePassword(account.getPassword(), account.getId()));
 accountDao.save(account);
} 

Stole

By stole on Aug 20, 2009 at 2:27 PM PDT

Ah. Sometimes one has to say a lot more in order not to repeat oneself.

By stole on Aug 20, 2009 at 10:19 PM PDT

The answer as to why you shouldn't change the code is simple. It may seam as a simplification to you, but in fact doing what you're proposing will make it harder to change the salt afterwards.

In case you want to switch from the id to something else as the salt you could simply change it in your security config.

p:userPropertyToUse="id" /> 
By muskatus on Sep 15, 2009 at 9:25 AM PDT

The main reason I would offer is this. There are two cases where you access the password: during account creation, and during authentication. A DaoAuthenticationProvider handles the authentication case and to use that, you need to inject it with a salt source. By using that same salt source during registration, you don't have to worry about manually syncing the two cases in the event that you decide to use something other than the ID: you would just change the XML configuration of the salt source itself.

Know that response is pretty late but hopefully it helps anyway.

By Willie Wheeler on Sep 16, 2009 at 12:40 AM PDT

...another way to say the same thing is that this is basically a DRY move.

By Willie Wheeler on Sep 16, 2009 at 12:45 AM PDT

I initially found your article because I couldn't find any documentation in Spring on how they mix the salt with the password. Thanks for letting me know about the braces e.g. password {salt}. By the way, how did you find that out? I'm frustrated that I couldn't find that from my reading of the documentation.

Decided to read your article and it cleared up a lot of confusion I had about the configuration - especially surrounding the authentication provider. I was declaring an authentication manager bean and the necessary list of providers. Nice to know I didn't need to do that but simply had to use the security:custom-authentication-provider tag!

Great article - thank you.

PUK

By PUK on Oct 27, 2009 at 8:02 AM PDT

I've got a question about configuration. I've got two configuration files: security in one xml config (referenced from web.xml), and another xml config for the main dispatcher servlet (dispatcher-servlet.xml).

I already have a userDAO which is configured in the dispatcher-servlet.xml. This needs to be dependency injected into the UserDetailsService so I've repeated the userDAO bean in the security xml config too. This repitition is bad.

Additionally, I want to use the password encoder and salt source within a controller bean. Therefore I need to DI the password encoder and salt source beans into the controller bean. They're defined in different xml files.

How does someone get around this problem?

Thanks,

PUK

By PUK on Oct 27, 2009 at 8:20 AM PDT

@PUK: Glad to know the article helped. Yeah, on the namespace config, that's a pretty nice feature. Behind the scenes it's still creating all the beans you'd normally create, but in effect the namespace config amounts to a domain-specific language that makes config more convenient and intuitive.

As far as finding out about the braces, it's been far enough back in time that I can't say for sure, but I'm about 90% confident that I had to dig into the source for that little gem. :-)

On your UserDao question and password encoder questions, I agree with you that DRY applies here. What I would do in the case you describe is have three separate bean config files:

  1. an applicationContext.xml for high-reuse object like the UserDao
  2. an applicationContext-security.xml for security objects so you can take advantage of the XML default namespace feature (so you don't have to repeat the "security:" prefix everywhere, and
  3. a main-servlet.xml (or whatever you want to call it) for your web config. The web config will be able to see your applicationContext.xml but not vice versa.

Just make sure you load the app configs from the context loader instead of from the DispatcherServlet.

By Willie Wheeler on Oct 27, 2009 at 11:48 AM PDT

@Willie: I really appreciate the immediate response! Previous to reading it I had arrived at this solution:

  1. applicationContext.xml (basically empty)
  2. commonBeans.xml (userDao and a couple of other beans)
  3. applicationContext-security.xml (import on commonBeans.xml followed by security configs)
  4. dispatcher-servlet.xml (import on commonBeans.xml followed by servlet configs)

This solution was born out of my lack of knowledge and assumptions of the contexts and configuration files. I had figured that each xml file might only be able to reference beans known to its file. I was also unsure about the hierarchy of the contexts.

Obviously I was worried about my "solution" because of the duplication of beans in memory and this was set to grow because security and servlet both need message sources from i18n, etc).

The bit in your response about the web config being able to see the applicationContext.xml was a revelation. The common stuff is in applicationContext.xml and it all works very well.

I know you must be very busy with books, blogs, and your own development so thanks again!

PUK

By PUK on Nov 1, 2009 at 2:04 AM PST

Post a comment

Your name:
Your e-mail address (won't be displayed):
Your web site (optional):
example: www.xyz.com
Your comment:
Preview:
By You
Please help us reduce comment spam:
Spring Annotations RefCard
Check out the new DZone Spring Annotations Refcard by Craig Walls!

What's New?

2009-08-30 - Check out my two-part series on DZone: Spring Integration: A Hands-On Tutorial.
2009-03-25 - My new article Getting Started with Spring Batch 2.0 is available on DZone.
Home | Consulting | Tech Articles | Mailing List | Contact | Spring Blog
Copyright © 2008 Wheeler Software, LLC.