1. 程式人生 > >spring security認證對密碼進行MD5認證

spring security認證對密碼進行MD5認證

在上一篇中寫了如何自定義資料庫使用者表結構,這裡補充一下怎麼對使用者輸入的密碼進行MD5認證,在老版本的spring security(筆者使用的是org.springframework.security:spring-security-core:5.0.0.M2)中可以找到一個org.springframework.security.authentication.encoding.Md5PasswordEncoder,要加密的話只需要:

@Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(new
Md5PasswordEncoder()) //對輸入的密碼進行MD5加密,在註冊時會將使用者密碼加密後放入資料庫 .usersByUsernameQuery("select userid,userpassword,enableflag " +"from ftp_user where userid=?") .authoritiesByUsernameQuery("select username, authority " +"from authorities where username=?"
); }

而在使用新的版本(spring-security-core-5.0.6.RELEASE)時,發現沒有這個包了,取而代之的是org.springframework.security.crypto.password.MessageDigestPasswordEncoder,新的MD5加密寫法如下:

@Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(new
MessageDigestPasswordEncoder("MD5")) .usersByUsernameQuery("select userid,userpassword,enableflag " +"from ftp_user where userid=?") .authoritiesByUsernameQuery("select username, authority " +"from authorities where username=?"); }

這裡使用的MessageDigestPasswordEncoder方法被標記為過時方法,原因為spring security不推薦這中加密方法,到該類的定義中可以看到:

* @deprecated Digest based password encoding is not considered secure. Instead use an
 * adaptive one way funciton like BCryptPasswordEncoder, Pbkdf2PasswordEncoder, or
 * SCryptPasswordEncoder. Even better use {@link DelegatingPasswordEncoder} which supports
 * password upgrades. There are no plans to remove this support. It is deprecated to indicate
 * that this is a legacy implementation and using it is considered insecure.

雖然被標記為過時方法,但是並沒有打算廢棄,還是能用的。