Hashing and Salting Passwords with Spring Security

2019-01-22 04:00发布

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

3条回答
乱世女痞
2楼-- · 2019-01-22 04:22

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

查看更多
老娘就宠你
3楼-- · 2019-01-22 04:26

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);
    }
}
查看更多
Anthone
4楼-- · 2019-01-22 04:41

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>
查看更多
登录 后发表回答