harry
harry

Reputation: 83

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:

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

Upvotes: 6

Views: 2271

Answers (2)

Shaun the Sheep
Shaun the Sheep

Reputation: 22742

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.

Upvotes: 6

Jigar Parekh
Jigar Parekh

Reputation: 6273

i think best way to do this is to specify password encoder to authentication provider some thing like below, for more information refer doc

<authentication-manager>
    <authentication-provider user-service-ref="userService">
        <password-encoder ref="passwordEncoder">
            <salt-source ref="saltSource" />
        </password-encoder>
    </authentication-provider>
</authentication-manager>


<beans:bean     class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"
    id="passwordEncoder" />

<beans:bean     class="org.springframework.security.authentication.dao.ReflectionSaltSource"
    id="saltSource">
    <beans:property name="userPropertyToUse" value="userName" />
</beans:bean>

Upvotes: 0

Related Questions