Hashing and Salting Passwords with Spring Security 3

落爺英雄遲暮 提交于 2019-11-27 11:43:13

问题


How can I hash passwords and salt them with Spring Security 3?


回答1:


Programmatic-ally you would do it as follows:

In your application-context.xml (defined in web.xml under contextConfigLocation) file define the bean (this example uses md5).

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

Then Autowire the password encoder:

@Autowired
PasswordEncoder passwordEncoder;

In your method or wherever you want to hash and salt.

passwordEncoder.encodePassword("MyPasswordAsString", "mySaltAsStringOrObject");

The above call should return a salted hash (as a String).

That should do it. I'm assuming you can figure out the jar's you'll need.

UPDATE

It should go without saying that using MD5 is not the best idea. Ideally you should use SHA-256 at least. This can be done with the ShaPasswordEncoder.

Replace the MD5 bean config above with:

<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
     <constructor-arg value="256"/>
</bean>



回答2:


Simplest seems to be Spring Security 3.1 assuming no constraints on the way hashing should be done:

<bean id="encoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>

<security:authentication-manager>
    <security:authentication-provider>
        <security:password-encoder ref="encoder"/>
        <security:jdbc-user-service data-source-ref="dataSource" users-by-username-query="select username,password, enabled from users where username=?" authorities-by-username-query="select u.username, ur.authority from users u, user_roles ur where u.username = ur.username and u.username =?"/>
    </security:authentication-provider>
</security:authentication-manager>


@Controller
@Stateless
public class UsersEJB {
    @PersistenceContext(unitName = "somePU")
    private EntityManager em;
    @Transactional
    public void create(Users users) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String hashedPassword = passwordEncoder.encode(users.getPassword());
        users.setPassword(hashedPassword);
        em.persist(users);
    }
}



回答3:


easiest way, as documented:

<authentication-manager alias="authenticationManager">
    <authentication-provider user-service-ref="userDetailsService" >
        <password-encoder hash="sha">
            <salt-source user-property="username"/>
        </password-encoder>
    </authentication-provider>
</authentication-manager>

HTH



来源:https://stackoverflow.com/questions/7378107/hashing-and-salting-passwords-with-spring-security-3

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