Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change password hashing algorithm when using spring security?

I'm working on a legacy Spring MVC based web Application which is using a - by current standards - inappropriate hashing algorithm. Now I want to gradually migrate all hashes to bcrypt. My high level strategy is:

  • New hashes are generated with bcrypt by default
  • When a user successfully logs in and has still a legacy hash, the app replaces the old hash with a new bcrypt hash.

What is the most idiomatic way of implementing this strategy with Spring Security? Should I use a custom Filter or my on AccessDecisionManager or …?

like image 524
harry Avatar asked Dec 07 '12 12:12

harry


1 Answers

You'll probably have to customize your AuthenticationProvider since that is where the password is actually compared with the user data and you have all the information you need available.

In the authenticate method, you would first load the user data. Then check the user-supplied password with both a BCryptPasswordEncoder and your legacy one. If neither returns a match, throw a BadCredentialsException.

If the user authenticates successfully (very important :-)) and the password is legacy format (the legacy encoder matched), you would then call some additional code to update the user's account data and replace the legacy hash with a bcrypt one. The BCryptPasswordEncoder can be also be used to create new hashes.

If you want, you could detect in advance whether the stored hash was already bcrypt before doing the comparisons. Bcrypt strings have quite a distinct format.

Note also that to make it harder to guess valid account names, you should try to make the method behave the same both when a supplied username exists and when it doesn't (in terms of the time it takes). So call the encoders even when you don't have any user data for the supplied username.

like image 107
Shaun the Sheep Avatar answered Oct 21 '22 05:10

Shaun the Sheep