1、自定义PasswordEncoder
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class MD5PasswordEncoder implements PasswordEncoder { @Override public String encode(CharSequence rawPassword) { return MD5Util2.encode(rawPassword.toString()); }
@Override public boolean matches(CharSequence rawPassword, String encodedPassword) { return encodedPassword.equals(MD5Util2.encode(rawPassword.toString())); }
}
|
使用到的Md5工具类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import java.security.MessageDigest;
public class MD5Util2 { private static final String SALT = "lwz"; public static String encode(String password) { password = password + SALT; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new RuntimeException(e); } char[] charArray = password.toCharArray(); byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++) byteArray[i] = (byte) charArray[i]; byte[] md5Bytes = md5.digest(byteArray); StringBuffer hexValue = new StringBuffer(); for (int i = 0; i < md5Bytes.length; i++) { int val = ((int) md5Bytes[i]) & 0xff; if (val < 16) { hexValue.append("0"); } hexValue.append(Integer.toHexString(val)); } return hexValue.toString(); } }
|
2、SpringSecurity处理MD5
其实这个就很简单了,就是在你save数据之前,调用一下加密的方法,也就是上面自定义的encoder。然后把拿到的用户明文密码填充进去。这里就不再赘述,重点看SpringSecurity处理,还是使用上篇中我们提到的UserDetails实现类,你只需要在返回User对象的时候将password从数据库中读取出来,传给SpringSecurity,它会自动匹配matches方法进行比对。所以我们的代码这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| @Component public class CustomUserService implements UserDetailsService { @Autowired AdminService adminService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Admin admin = adminService.findAdminByUsername(username); if (admin==null){ throw new UsernameNotFoundException("用户名不存在"); } List<SimpleGrantedAuthority> authorities = new ArrayList<>(); for (Role role : admin.getRoles()) { authorities.add(new SimpleGrantedAuthority(role.getName())); } return new User(admin.getUsername(),admin.getPassword(),true,true,true,true,authorities); } }
|
然后的处理就很简单了,我们只需要把自己的PasswordEncoder以Bean的形式告诉SpringSecurity,可以理解为:告诉SpringSecurity我要用我自定义的Encoder来处理密码,你去调用它。所以我们在LoginSecurityConfig(就是你实现了WebSecurityConfigurerAdapter抽象类的那个方法 )注册一个bean就好了,如下:
SecurityConfig类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Bean public PasswordEncoder passwordEncoder() { return new MD5PasswordEncoder(); }
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(customUserService()); }
|