Shiro加密之后的认证
之前的用户信息的密码使用的是明文,在实际项目中是不可取的,接下来我们使用Shiro安全框架学习信息加密。
接着上一篇的代码,我们修改一下,使用加密之后的认证。
1public class CostomRealTest {
2 @Test
3 public void costomRealTest(){
4 ConstomRealm constomRealm =new ConstomRealm();
5 DefaultSecurityManager defaultSecurityManager =new DefaultSecurityManager();
6 defaultSecurityManager.setRealm(constomRealm);
7
8 //使用MD5加密
9 HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
10 //设置加密算法名称
11 matcher.setHashAlgorithmName("md5");
12 //设置加密次数
13 matcher.setHashIterations(1);
14 constomRealm.setCredentialsMatcher(matcher);
15
16 //构建setSecurityManager环境
17 SecurityUtils.setSecurityManager(defaultSecurityManager);
18 Subject subject = SecurityUtils.getSubject();
19 UsernamePasswordToken token =new UsernamePasswordToken("jiuyue","12345");
20 subject.login(token);
21 System.out.println("sAuthenticated:"+subject.isAuthenticated());
22 subject.checkRole("admin");
23 subject.checkRoles("user","admin");
24 subject.checkPermission("user:add");
25
26 }
27
28}
使用加密之后的认证,说明我们之前数据库中存储的用户信息也是使用相同算法md5加密的。这里模拟的是用户的密码为12345并且已经加密处理存储在数据库中了。
1 Map<String,String> userMap = new HashMap<>();
2 {
3 String password="12345";
4 Md5Hash md5Hash = new Md5Hash(password);
5 System.out.println("密文:"+md5Hash.toString());
6 userMap.put("jiuyue",md5Hash.toString());
7 super.setName("costomReal");
8 }
Shiro加密之后加盐
很多时候密码除了要进行加密处理,往往还要进行加盐处理存储在数据库中,这里加盐"jiuyue"。
1 Map<String,String> userMap = new HashMap<>();
2 {
3 String password="12345";
4 //Md5Hash md5Hash = new Md5Hash(password);
5 Md5Hash md5Hash = new Md5Hash(password,"jiuyue");
6 System.out.println("密文:"+md5Hash.toString());
7 userMap.put("jiuyue",md5Hash.toString());
8 super.setName("costomReal");
9 }
存储的数据是加盐的,那么在认证的时候就要把盐返回
1 @Override
2 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
3 //1、从主体中获取认证信息的用户名
4 String userName = (String) token.getPrincipal();
5 //2、通过用户名获得密码
6 String password = getPasswordByUserName(userName);
7 if (password==null){
8 return null;
9 }
10 SimpleAuthenticationInfo simpleAuthenticationInfo =
11 new SimpleAuthenticationInfo(userName,password,"customReal");
12
13
14simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("jiuyue"));
15 //这里要把盐也返回(如果密码做加密处理的时候也加了盐的话),真实项目中这里不该写死
16 return simpleAuthenticationInfo;
17 }
专题链接:
Shiro安全框架第一篇| 什么是Apache Shiro?
Shiro安全框架第四篇| Shiro自定义Realm进行认证授权
Shiro安全框架第五篇| 使用JdbcRealm进行认证授权
“扫码关注“