Hashing and Salting Passwords with Spring Security 3

前端 未结 3 890
無奈伤痛
無奈伤痛 2020-12-13 15:53

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

相关标签:
3条回答
  • 2020-12-13 16:00

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-13 16:07

    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>
    
    0 讨论(0)
  • 2020-12-13 16:08

    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

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