该项目是根据上篇《Spring Boot 整合Shiro(一)登录认证和授权(附源码)》进行配置,若有不明白的请先查看上篇文章。
1.加密工具
用户注册时的密码用这个加密保存数据库
-
/**
-
* 账户密码加密
-
* @param username
-
* @param pwd
-
* @return
-
*/
-
public static String MD5Pwd(String username, String pwd) {
-
String hashAlgorithmName =
"MD5";
//加密方式
-
Object crdentials = pwd;
//密码原值
-
ByteSource salt = ByteSource.Util.bytes(username);
//以账号作为盐值
-
int hashIterations =
1024;
//加密1024次
-
return
new SimpleHash(hashAlgorithmName,crdentials,salt,hashIterations).toString();
-
-
}
2.Shiro配置
2.1修改ShiroConfig
添加以下方法:
-
/**
-
* 加密配置
-
* @return
-
*/
-
@Bean(name =
"credentialsMatcher")
-
public HashedCredentialsMatcher hashedCredentialsMatcher() {
-
HashedCredentialsMatcher hashedCredentialsMatcher =
new HashedCredentialsMatcher();
-
// 散列算法:这里使用MD5算法;
-
hashedCredentialsMatcher.setHashAlgorithmName(
"md5");
-
// 散列的次数,比如散列两次,相当于 md5(md5(""));
-
hashedCredentialsMatcher.setHashIterations(
1024);
-
// storedCredentialsHexEncoded默认是true,此时用的是密码加密用的是Hex编码;false时用Base64编码
-
hashedCredentialsMatcher.setStoredCredentialsHexEncoded(
true);
-
return hashedCredentialsMatcher;
-
}
修改customRealm:
-
@Bean
-
public CustomRealm customRealm() {
-
CustomRealm customRealm =
new CustomRealm();
-
// 告诉realm,使用credentialsMatcher加密算法类来验证密文
-
customRealm.setCredentialsMatcher(hashedCredentialsMatcher());
-
customRealm.setCachingEnabled(
false);
-
return customRealm;
-
}
2.2修改CustomRealm
当中“password”参数值是用户注册时使用加密工具生产保存的密码,可在CustomRealm中配置UserService。
-
/**
-
* 身份认证
-
* 这里可以注入userService,为了方便演示直接写死账户和密码
-
* 获取即将需要认证的信息
-
* @param authenticationToken
-
* @return
-
* @throws AuthenticationException
-
*/
-
@Override
-
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
-
System.out.println(
"-------身份认证方法--------");
-
String userName = (String) authenticationToken.getPrincipal();
-
// String userPwd = new String((char[]) authenticationToken.getCredentials());
-
//根据用户名从数据库获取密码
-
String password =
"89267a06ce552c28e3edc11be28e4f80";
// 使用账户和明文密码:123加密后
-
// if (userName == null) {
-
// throw new AccountException("用户名不正确");
-
// } else if (!userPwd.equals(password )) {
-
// throw new AccountException("密码不正确");
-
// }
-
-
//交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
-
ByteSource salt = ByteSource.Util.bytes(userName);
-
return
new SimpleAuthenticationInfo(userName, password, salt, getName());
-
}
3.实战演练
使用账户:aa和密码:123 进行测试,可以看到提示登录成功。
之前的密码是根据账户和密码进行处理的,要注意的是注册的加密方式和设置的加密方式还有Realm中身份认证的方式都是要一模一样的
下篇介绍《Spring Boot 整合 Shiro(三)Kaptcha验证码》