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.

虽然被标记为过时方法,但是并没有打算废弃,还是能用的。

你可能感兴趣的:(笔记)