Spring Security Salt

给你一囗甜甜゛ 提交于 2019-12-02 15:53:53
Roadrunner

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.:

<bean id="saltSource"
    class="org.springframework.security.authentication.dao.ReflectionSaltSource"
    p:userPropertyToUse="username" />

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

<bean id="daoAuthenticationProvider"
    class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"
    p:passwordEncoder-ref="passwordEncoder"
    p:saltSource-ref="saltSource"
    p:userDetailsService-ref="userDetailsService" />

<authentication-manager>
    <authentication-provider ref="daoAuthenticationProvider" />
</authentication-manager>

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;
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!