此功能模块我们最好还是配合上用户注册
功能进行测试, 定义如下UserController:
@PostMapping("/register")
public String register(String username, String password){try {userService.insertUser(username, password);return "login";} catch (Exception e) {throw new RuntimeException(e);}
}
定义UserServiceImpl::insertUser
方法:
@Service
public class UserServiceImpl {@Resourceprivate UserMapper userMapper;// ...public void insertUser(String username, String password) throws Exception {// Md5Hash md5Hash = new Md5Hash(password); // 进行 MD5 加密String salt = "mysalt"; // 实战中盐可以随机password = new Md5Hash(password, salt).toHex(); // md5(盐 + 密码)User user = new User();user.setUsername(username);user.setPassword(password);user.setPasswordSalt(salt); // 设置盐userMapper.insertUser(user); // 最终将盐也添加进去.}
}
而UserMapper接口定义如下:
public void insertUser(User user);
/* 实现:<insert id="insertUser" parameterType="User">INSERT INTO `tb_users` VALUES(NULL, #{username}, #{password}, #{passwordSalt});</insert>
*/
随后我们在MyRealm::doGetAuthenticationInfo
方法中将盐返回给SecurityManager:
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {// subject.login(token) 会调用到这里UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token; // 认证时, 强制转换String username = usernamePasswordToken.getUsername(); // 得到用户名User user = userMapper.queryUserByUserName(username); // 从数据库中查询该用户名, 得到该用户信息if (user != null) {// 成功从数据库中查询到用户, 我们就将用户的信息封装到 AuthenticationInfo 中, SimpleAuthenticationInfo 是 AuthenticationInfo 的子类return new SimpleAuthenticationInfo(username, user.getPassword(), ByteSource.Util.bytes(user.getPasswordSalt()), this.getName()); // 注意这里的 ByteSource.Util.bytes(user.getPasswordSalt()) 用于返回盐// new SimpleAuthenticationInfo(用户名, 用户密码, 当前盐, 当前Realm名称)}return null;
}
测试完毕后, 我们需要将数据库其他用户账号密码统一改为加盐模式, 否则其他用户无法登录:
mysql> update tb_Users set password_salt = '7788', password = MD5(CONCAT(password_salt, '123456')) WHERE user_id < 6; -- 其他用户密码统一设置为123456
Query OK, 5 rows affected (0.11 sec)
Rows matched: 5 Changed: 5 Warnings: 0mysql> SELECT * FROM tb_Users;
+---------+----------+----------------------------------+---------------+
| user_id | username | password | password_salt |
+---------+----------+----------------------------------+---------------+
| 1 | zhangsan | e97e4623f9bb7f1280233bfbe2793e70 | 7788 |
| 2 | lisi | e97e4623f9bb7f1280233bfbe2793e70 | 7788 |
| 3 | wangwu | e97e4623f9bb7f1280233bfbe2793e70 | 7788 |
| 4 | zhaoliu | e97e4623f9bb7f1280233bfbe2793e70 | 7788 |
| 5 | chenqi | e97e4623f9bb7f1280233bfbe2793e70 | 7788 |
| 6 | heihu577 | d23170a6c09cb22ef2b690406d86cd64 | mysalt |
+---------+----------+----------------------------------+---------------+
6 rows in set (0.00 sec)