因为在实际应用中用户密码不会使用明文保存,最广泛的是使用md5 sha等不可逆的加密算法将密码加密后存入数据库,所以在认证的时候也要将登录请求中的密码做同样的加密才能与数据库中数据做比对。
创建用户
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@Getter @Setter public class User implements Serializable { private String id; private String username; private String password; private String salt; public User(String username, String password) { this.id = UUID.randomUUID().toString().replace("-", ""); this.username = username; this.salt = getId().substring(0, 6); this.password = new Sha512Hash(password, getSalt()).toString(); } }
创建数据源
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class UserService { private static final Map<String, User> userMap = new HashMap<>(); static { userMap.put("admin1", new User("admin1", "123456")); userMap.put("admin2", new User("admin2", "123456")); } public static User getUserByName(String name) { return userMap.get(name); } }
修改MyRealm
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; String name = token.getUsername(); String password = String.valueOf(token.getPassword()); User user = UserService.getUserByName(name); if (null == user) { return null; } else { String credentials = new Sha512Hash(password, user.getSalt()).toString(); token.setPassword(credentials.toCharArray()); return new SimpleAuthenticationInfo(user, user.getPassword(), getName()); } }