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 for authentication against secured passwords

When discussing secure storage of passwords, there are really two different sides to consider. First, during the registration process (or else during account provisioning, if that's how you're doing things), you have to obfuscate the password in some fashion before saving it to the data store. And secondly you have to be able to use those obfuscated passwords during authentication.

We're going to start with the authentication part first, since that's pretty easy to set up. We're going to assume the following:

  • Your app has an existing user account model is called Account, with a corresponding AccountDao interface and implementation to support CRUD operations.
  • You also have a service bean, which we'll assume is AccountServiceImpl, that supports user registrations. The registrations store the passwords as plaintext.
  • Your app is configured to support Spring Security 2 username/password authentication against plaintext passwords. You're using two separate application context files: applicationContext.xml and applicationContext-security.xml, and you're using namespace configuration in applicationContext-security.xml.

Given the assumptions above, it isn't hard to modify the configuration to use hashed passwords during the login process. Let's see how.

Create some user accounts in the database with hashed passwords

Create an account or two in your database with SHA-1 hashed passwords. You can use the following website to compute SHA-1 hashes of plaintext passwords:

http://sha1-hash-online.waraxe.us/

For example, the SHA-1 hash of flower is 5a46b8253d07320a14cace9b4dcbf80f93dcef04. When entering your hash into the hash calculator at the link above, be sure not to enter a carriage return character, as that's significant and will completely change the hash. Anyway, create the database records, using the SHA-1 hash as the password.

Update applicationContext-security.xml to authenticate against hashed passwords

We want to add something called a PasswordEncoder to our Spring configuration. PasswordEncoder is an interface defining a contract for computing hashes. There are different PasswordEncoder implementations according to the hash function you want to apply. Two popular options, for example, are Md5PasswordEncoder for MD5 hashes and ShaPasswordEncoder for (you guessed it) SHA. We'll use SHA here but either choice is legitimate. Don't use Md4PasswordEncoder unless you are working with a legacy system, as it is known to be weak.

The namespace configuration supports PasswordEncoders. Just add a single line to your authentication-provider element like this:

<authentication-provider>
	<password-encoder hash="sha" />
	<jdbc-user-service data-source-ref="dataSource" />
</authentication-provider>

Yep, that's it! This configuration sets SHA-1 as our hash algorithm.

Try it out

Try logging in using the account you just created. Type in the plaintext password, not the hash. The login should work. If so, congratulations, your app authenticates against secure passwords! (You'll need to convert whatever other passwords you have into SHA-1 hashes.)

Now we're going to jump over to the other side, which is storing passwords securely during either the registration or account provisioning process. We'll assume a registration process but the technique is the same in either case.

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 in Practice
My brother and I are writing Spring in Practice for Manning!

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.