shiro自学总结
1 shiro是啥:
shiro是一个权限管理框架,主要分为四大部分,认证,授权,密码管理,会话管理
shiro架构
主要关注:
subject:主体 可以是登录的用户,或者各种与自己对接的系统
Security Manager: 会话管理器 :shiro的核心部分(认证器,授权器,realm(最重要))
realm:可以理解为认证授权校验的 类似datasource数据源
认证流程:
认证流程开发
1:引入jar包
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.5.3</version>
</dependency>
2: 模仿数据库的数据 shiro有一个.ini文件模仿数据库文件 (方便自学)
3:开发认证代码
到此最简单的shiro认证流程完成
上图的realm是从配置文件中读取的,实际开发中需要从数据库读取
问题 认证流程在realm中完成,所以需要自定义realm,以满足实际开发中的个性化定义
自定义realm就需要知道realm的源码关系
AuthonticatingRealm:认证realm
AuthorizingRealm:授权realm
SimpleAccoutRealm 继承上面2个类 所以我们需要自定义Realm 就需要继承SimpleAccoutRealm 实现里面的2个方法
doGetAuthorizationInfo()方法 授权器
doGetAuthenticationInfo()方法 认证器
2 自定义realm
1:自定义realm继承AuthorizingRealm
2:测试
对于登录来说,用户的密码需要加密 shiro提供了这个功能
但如何在realm中使用realm加密呢
3 自定义Realm加密
1:自定义realm
public class CustomerMd5Realm extends AuthorizingRealm {
//授权器
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
//认证器
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
Object principal = token.getPrincipal();
if ("xiaoye".equals(principal)){
//没有加密
//return new SimpleAccount("xiaoye","123",this.getName());
//md5加密
// return new SimpleAccount("xiaoye","202cb962ac59075b964b07152d234b70",this.getName());
//MD5 +salt(盐)
// return new SimpleAuthenticationInfo(principal,"200820e3227815ed1756a6b531e7e0d2", ByteSource.Util.bytes("qwe"),this.getName());
//md5+ salt+hash散列
return new SimpleAccount(principal,"d3f33ea3d8aef9caf20fac7a5c02b7da",ByteSource.Util.bytes("qwe"),this.getName());
}
return null;
}
}
2:测试
public static void main(String[] args) {
//1 设置shiro管理器 将realm设置到中间
CustomerMd5Realm customerMd5Realm = new CustomerMd5Realm();
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
//设置加密方式
hashedCredentialsMatcher.setHashAlgorithmName("md5");
hashedCredentialsMatcher.setHashIterations(2048);
customerMd5Realm.setCredentialsMatcher(hashedCredentialsMatcher);
DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager(customerMd5Realm);
SecurityUtils.setSecurityManager(defaultSecurityManager);
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken xiaoye = new UsernamePasswordToken("xiaoye", "123");
try {
subject.login(xiaoye);
System.out.println("登录成功");
} catch (UnknownAccountException e) {
e.printStackTrace();
System.out.println("用户名错误");
}catch (IncorrectCredentialsException e){
e.printStackTrace();
System.out.println("密码错误");
}
}