2

As Spring Security 3.1 provides a new convenient PasswordEncoder and an implementation StardardPasswordEncoder, I try to implement them into current project. However, there is question about how the PasswordEncoder should work when save/verify user password. Here is code for the new PasswordEncoder:

    private static final String SALT_AS_TOP_SECRET = "mysalt"; 
    private static final PasswordEncoder encoder = new StandardPasswordEncoder(
        SALT_AS_TOP_SECRET);

    public static String encrypt(String rawPassword) {
        return encoder.encode(rawPassword);
    }

    public static boolean match(String rawPassword, String password) {
        return encoder.matches(rawPassword, password);
    }

My applicaiton is Spring with JPA, so there is a User entity implements UserDetails with basic getter/setter for the password, also there is a service class implement the UserDetailService in the service layer.

I am confused about the UserDetailService only requires a loadUserByUsername method which doesn't check password. So here are other questions:

  1. Where shall I place the match method from PasswordEncoder?
  2. Shall I implement another interface for the service class?
  3. Shall I give any logic within User entity when setting password?
  4. As the new PasswordEncoder interface is independent to other security package, I bet there is no need to initiate/inject the bean from xml? I try to pu the salt inside the class instead of external storage.

Please give a hint, thanks in advance.

Dreamer
  • 7,333
  • 24
  • 99
  • 179
  • 3
    The password encoder should be injected into the `AuthenticationProvider`, which is responsible for authenticating the user. Please see [this answer](http://stackoverflow.com/questions/8521251/spring-securitypassword-encoding-in-db-and-in-applicationconext/8528804#8528804) for an example. – Shaun the Sheep Jan 23 '13 at 00:42
  • @Luke Taylor. thank you. In the example the password is encoded in JDBC as POJO. but how to encrypt the password with PasswordEncoder on JPA entity class? Here is a question for a better design, as we want the encryption salted so it seems we have to put the salt into a external source, otherwise need to place the salt in both application-security.xml(authentication) and POJO(encrypt password), so is there better solution to make the salt internal(hard coded in POJO)? Thank you. – Dreamer Jan 23 '13 at 15:43
  • 1
    You would be better using BCrypt, as described in that answer. To encode the password just call `passwordEncoder.encode(password)`. Where you do it is up to you. I can't say since I don't really know how your application is implemented. Presumably you can do it when you are creating a new JPA entity? – Shaun the Sheep Jan 23 '13 at 17:39

0 Answers0