一、前言
1、SpringBoot整合mybaties
2、SpringBoot整合Shiro实现登录鉴权
2、SpringBoot整合Shiro实现前后台分离Token鉴权
我们在数据库里存的用户密码是明文,这显然是不行的。要解决这个问题,就需要对密码进行加盐md5后存进数据库。忽略http传输密码明文,不是此文重点。
二、上代码
0.代码变更
modified: src/main/java/com/yx/shiro/CustomRealm.java
modified: src/main/java/com/yx/shiro/shiroConfig.java
modified: src/main/java/com/yx/controller/UserController.java
image.png
1./com/yx/shiro/CustomRealm.java
只放变更部分
/**
* Shiro自带密码管理器
*
* @return HashedCredentialsMatcher
*/
public HashedCredentialsMatcher hashedCredentialsMatcher() {
//Shiro自带加密
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
//散列算法使用md5
credentialsMatcher.setHashAlgorithmName("md5");
//散列次数,2表示md5加密两次
credentialsMatcher.setHashIterations(1);
return credentialsMatcher;
}
//将自己的验证方式加入容器
@Bean
public CustomRealm myShiroRealm() {
CustomRealm customRealm = new CustomRealm();
//加入密码管理
customRealm.setCredentialsMatcher(hashedCredentialsMatcher());//设置Shiro自带密码管理器
return customRealm;
}
2./com/yx/shiro/shiroConfig.java
/**
* 用于认证
* 每一次调用subject.login都会通过这个方法来实现认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
if (StringUtils.isEmpty(authenticationToken.getPrincipal())) {
return null;
}
//从主体中获取用户名
String name = authenticationToken.getPrincipal().toString();
//从数据库中查出用户信息
User user = userMapper.queryByName(name);
if (user == null) {
//这里返回后会报出对应异常
return null;
} else {
//这里验证authenticationToken和simpleAuthenticationInfo的信息
SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, user.getPassword().toString(), getName());
simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("YX")); //加盐
return simpleAuthenticationInfo;
}
}
3./com/yx/controller/UserController.java
这里修改修改注册接口,将前端传来的密码明文加盐MD5存储到数据库
@RequestMapping(value = "/register", method = RequestMethod.POST)
public Object register(HttpServletRequest request, @RequestBody User user) {
//将前台传的密码加盐md5后存入数据库
user.setPassword(new Md5Hash(user.getPassword(), "YX").toString());
//将用户信息插入到数据库中
int add = userServices.add(user);
return ApiResult.success(add);
}
三、Postmain测试
0.明文密码注册
image.png
1.加盐MD5存储与数据库
image.png
2.登录成功
image.png