1.在添加用户时,对用户的密码进行加密存储
改写实现类
@Override
public void save(Employee employee) {
/*在保存时将密码进行加密*/
Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName(),2);
employee.setPassword(md5Hash.toString());
//保存员工信息
int m = employeeMapper.insert(employee);
if(m<1){
throw new LogicException("增加失败!");
}
//查询员工编号
//保存关系表数据
//先查询数据
Employee emp=employeeMapper.findByUserNameAndPassword(employee.getName(),employee.getPassword());
//循环增加关系表数据
Long[] ids= employee.getIds();
if(ids!=null&&ids.length>0) {
for (Long id : ids) {
int n = employeeRoleMapper.insert(new EmployeeRole(emp.getId(), id));
if (n < 1) {
throw new LogicException("增加失败!");
}
}
}
}
2.在用户登陆时将输入的密码与数据库进行比对的方式
在shiro中配置密码加密的凭证
<!--进行密码加密的凭证-->
<!--指定当前需要使用的凭证匹配器-->
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 指定加密算法 -->
<property name="hashAlgorithmName" value="MD5"/>
<property name="hashIterations" value="2"></property>
</bean>
1.在登陆时,要现将用户输入的密码转换成MD5格式再与数据库中的数据进行对比
@PostMapping("/login")
@ResponseBody
public ResultBean login(String username, String password, HttpSession session){
try {
/*对密码进行加密*/
password = new Md5Hash(password, username, 2).toString();
//令牌
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
SecurityUtils.getSubject().login(token);
return ResultBean.success();
} catch (UnknownAccountException e) {
return ResultBean.fail( "账号不存在");
} catch (IncorrectCredentialsException e) {
return ResultBean.fail( "密码错误");
} catch (Exception e) { e.printStackTrace();
return ResultBean.fail( "登录异常,请联系管理员");
}
}
2.在数据源的认证中对密码进行加密
/**
* 认证方法
* @param authenticationToken
* @return AuthenticationInfo
* 返回值AuthenticationInfo 如果为null 验证失败
* 返回的info中要具有真实的密码
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//获取用户名
String username = (String)authenticationToken.getPrincipal();
//获取密码
//authenticationToken.getCredentials();
Employee employee = employeeService.selectByUserName(username);
if(employee==null){
return null;
}
//返回用户的所有信息
/*盐
* ByteSource.Util.bytes(employee.getName()) 是将用户名转换为盐
* */
SimpleAuthenticationInfo ret=new SimpleAuthenticationInfo(employee,employee.getPassword(), ByteSource.Util.bytes(employee.getName()),this.getName());
return ret;
}
注意:1和2两个方法使用一个就可以