Spring Security Salt

前端 未结 1 944
既然无缘
既然无缘 2021-01-30 18:09

I\'m trying to add a salt when adding a new user/pwd, but the docs seem to be missing how to do this.

Here\'s a basic example:



        
1条回答
  •  没有蜡笔的小新
    2021-01-30 18:33

    You don't autowire the SaltSource when adding user. The SaltSource is an abstraction used by Spring to provide the source of the salt for password checking only.

    To create a properly encoded password hash You just past the salt itself to the PasswordEncoder - the value of username property, not the SaltSource:

    private PasswordEncoder encoder = new Md5PasswordEncoder();
    
    public User createUser(String username, String plainTextPassword) {
        User u = new User();
        u.setUsername(username);
        u.setPassword(encoder.encodePassword(plainTextPassword, username));
        getEntityManager().persist(u); // optional
        return u;
    }
    

    Moreover the autowire of SaltSource won't work until it's defined as an inner bean. You could define the ReflectionSaltSource as top level bean and pass it's ID to the password-encoder, i.e.:

    
    
    
    
    
    
    
        
    
    

    And then:

    @Autowired private PasswordEncoder passwordEncoder;
    @Autowired private SaltSource saltSource;
    
    public CustomUserDetails createUser(String username, String plainTextPassword) {
        CustomUserDetails u = new CustomUserDetails();
        u.setUsername(username);
        u.setPassword(passwordEncoder.encodePassword(
                plainTextPassword, saltSource.getSalt(u)));
        getEntityNamager().persist(u); // optional
        return u;
    } 
    

    0 讨论(0)
提交回复
热议问题