PasswordEncoder是spring-security的一个接口,主要用于对密码进行编码或加密,它有什么用途呢?说白了就是俩字“安全”,它的作用就是为了让密码不要以明文形式保存在数据库或其他文件中,我们先看一下这个接口的源码,如下:
public interface PasswordEncoder {
/**
* Encode the raw password. Generally, a good encoding algorithm applies a SHA-1 or
* greater hash combined with an 8-byte or greater randomly generated salt.
*/
String encode(CharSequence rawPassword);
/**
* Verify the encoded password obtained from storage matches the submitted raw
* password after it too is encoded. Returns true if the passwords match, false if
* they do not. The stored password itself is never decoded.
*
* @param rawPassword the raw password to encode and match
* @param encodedPassword the encoded password from storage to compare with
* @return true if the raw password, after encoding, matches the encoded password from
* storage
*/
boolean matches(CharSequence rawPassword, String encodedPassword);
}
很简单,只有两个方法:encode和matches,顾名思义,encode是对明文密码进行编码,生成一段不明所以的字符串,encode方法主要用于保存密码至数据库或其他文件前将密码进行编码。matches方法用于将原始密码与编码过的密码进行匹配,matches方法主要用于验证密码的正确性。
默认情况下,spring-security自带了常用的PasswordEncoder实现,比如默认的BCryptPasswordEncoder, Pbkdf2PasswordEncoder,SCryptPasswordEncoder,NoOpPasswordEncoder等。
那么,我们在spring-security中是如何使用PasswordEncoder的呢?
// 实例化一个PasswordEncoder的bean
@Bean
public PasswordEncoder passwordEncoder() {
DelegatingPasswordEncoder passwordEncoder = (DelegatingPasswordEncoder) PasswordEncoderFactories
.createDelegatingPasswordEncoder();
passwordEncoder.setDefaultPasswordEncoderForMatches(new BCryptPasswordEncoder());
return passwordEncoder;
//还有一种更简单的方法
// return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationProvider daoAuthenticationProvider(Us

本文介绍了Spring Security的PasswordEncoder接口,用于密码的安全编码,避免明文存储。文章讲解了其核心方法encode和matches的用途,并探讨了不同实现,如BCryptPasswordEncoder、Pbkdf2PasswordEncoder和DelegatingPasswordEncoder。DelegatingPasswordEncoder的引入是为了处理不同版本间的兼容性问题。最后,指出了PasswordEncoder在 DaoAuthenticationProvider 中的角色,用于验证用户密码的正确性。
最低0.47元/天 解锁文章
4575

被折叠的 条评论
为什么被折叠?



