xamad
Photo credit: xamad
del.icio.us Digg DZone Reddit StumbleUpon
1 | 2 | 3 | 4 | 5 | 6 | Next »
Software Development

Hashing and Salting Passwords with Spring Security 2

Use Spring Security 2 to store your user passwords securely.

[Author's note: This article was originally written as a recipe for the book Spring in Practice, which my brother John and I are writing for Manning Publications, but we just didn't have enough room to include it. It's still (we think, anyway) a great recipe, so we're making it available here free of charge. This will give readers of this website a chance to see the sort of recipe we're including in our book.

This material is based upon another article on this website called Storing Passwords Securely. The difference is that Storing Passwords Securely is not Spring-specific, whereas the present article is. — Willie]

Prerequisites

4.3 Save user registrations

Key Technologies

Spring Security, hash functions (e.g., MD5, SHA-1)

Background

When you're building an application involving user passwords, one of the challenges is to protect the passwords from prying eyes. We generally want to protect user registration data in transit from the browser to the server to prevent eavesdroppers on the network from getting at that data. But it's not enough to protect the data in transit. It's as important to store it securely.

It may not be immediately clear why you need to store the passwords securely. If, for instance, you have a corporate firewall that prevents the bad guys on the outside from getting to your password store, then why bother?

There are a few different answers to that. First, one basic security principle is to take a layered approach. There are no security silver bullets, and so overreliance on any particular process or technology (such as firewalls) creates unnecessary risk. Storing passwords securely gives you protection if a bad guy somehow gets in. (And it happens.)

A second answer is that the question makes the faulty assumption that the bad guys are on the outside. In an organization of any size, you can't be sure that you don't have bad guys on the inside, and the last thing you want them to do is use user passwords to log into your websites, or even other websites. The latter is a real concern since many users tend to use the same (or similar) passwords on multiple sites.

A third answer is that even if your organization is small (maybe it's just you), you'd like to be able to tell your users in your privacy policy that their passwords are stored securely, and that no one—not even the technical folks who administer the site—has any ability to see the stored passwords. That gives your users greater confidence that their information is safe and that you're taking security seriously.

So let's get to it!

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

Comments (18)

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

Hi, I want my password to be hashed and stored in a xml file using a simple hash function may be using MD5. Request you to please provide me some sample code for the same to hash my passowrd and store it in a xml file. Thanks Amit

By Amit on May 6, 2010 at 12:00 AM PDT

he myth of pandora is ancient, appears in several distinct Greek versions, pandora armbandand has been interpreted in many ways. In all literary versions, Neu Eingetroffen however, Pandora Armbänder the myth is a rosetta stone kind of theodicy, addressing the question pop information, web easy get, sports fashion, news-fashionof why there is evil in the world. In the seventh hot-winter century BC, Hesiod, both in his Theogony (briefly, without naming Pandora outright rosetta stone language, rosetta stone spanish, abercrombie and fitch, Abercrombie Fitch

By pandora schmuck on Aug 30, 2010 at 11:13 PM PDT

404336349d6e8317210e48fb6be50a3f

By ROZINE on Sep 1, 2010 at 5:32 PM PDT

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.